Displaying a div upon hovering over another div is resulting in numerous server requests and a flickering effect

I am attempting to create a hover effect where one div floats next to another. The layout of the divs is like a grid, placed side by side. Check out my code on this fiddle.

Using plain JavaScript, I want to display a second div (div2) floating next to div1 when hovering over it.

Example:

<div class="div1" onmouseover=getDetails()>

  </div>
  <div class="div2">

  </div>

function getDetails() {
 let html ="";
  return fetch('https://www.google.com')
  .then((response)=> {
    response.json().then((data) => {
      html += `
    <div>Hello world</div>

      `;
      document.getElementsByClassName("div2")[index].innerHTML = html;
      document.getElementsByClassName("div2")[index].style.display = "block";

    });

  });
}

However, I noticed that setting display: block on div2 triggers multiple server requests and causes flickering on hover. This seems to be due to repeated calls to the server. I'm unsure if this issue stems from CSS or JavaScript.

Any suggestions on how to address this would be greatly appreciated! Thank you.

Answer №1

Follow these steps to achieve it:

window.requestInProgress = false;
document.getElementById('targetHoverComponent').addEventListener('mouseover', () => {
if (window.requestInProgess !== true) {
  document.getElementById('targetConentComponent').innerHTML='Loading....';
    getDetailsAsync().then((bio) => {
    document.getElementById('targetConentComponent').innerHTML=bio; //Ensure to check for xss attacks.
    });
  }
});

async function getDetailsAsync() {
console.log('inside async');
  window.requestInProgress = true;
  const response = await fetch(`https://api.github.com/users/saurabhnemade`);
  const jsonResponse = await response.json();
  //console.log(jsonResponse.bio);
  window.requestInProgress = false;
  return await jsonResponse.bio;
}
.search-component-row-container {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.search-component {
  padding: 10px;
}

.criteria {
  padding: 10px;
  display: flex;
  align-items: center;
}

.criteria-onhover {
  display: none;
}

.criteria:hover ~.criteria-onhover{
  display: block;
}
<div class="search-component">
          <div class="search-component-row-container">
              <div class="criteria" id="targetHoverComponent">
                Div on which hover is required
              </div>
              <div class="criteria-onhover" id="targetConentComponent">
                Hidden Div Contents which appears on hover
              </div>
          </div>
</div>

Visit this fiddle link: https://jsfiddle.net/j05mg1xy/3/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preserving reference equality while passing props in React

Consider a scenario where a function dynamically generates some props for a component, and you want to pass all of them without specifying each individual prop that the function might generate. Typically, this can be achieved using the spread operator. How ...

Issue with Camera inversion not functioning properly in THREE.js with 1 Renderer and 2 Viewports

Check out this JSFiddle example In my project, I have a single scene with two cameras. Each camera is assigned to its viewport, and both viewports are placed side by side on the same renderer object. My goal is to have the second camera display a mirrore ...

Harness the power of JavaScript to generate a dynamic overlay with a see-through image that can be expanded

Within different sections of my website, we display banner ads that are loaded in real-time from third-party sources and come in various sizes. I'm interested in adding a transparent overlay image to each ad which would allow me to trigger a click ev ...

Exclude mock files from webpack configuration in AngularClass/angular2-webpack-starter for production builds

I've encountered some obstacles while working with the AngularClass/angular2-webpack-starter framework, specifically in configuring its webpack settings. My goal is straightforward, yet I've been struggling to achieve it. In my project directory ...

The utilization of the <span> tag featuring a {float:right] property causes container expansion in Internet Explorer 7

Within my HTML code, I have an A tag button that contains a Span element to hold icons. This setup functions correctly in most browsers, except for IE7. When I attempt to float the Span to the right side using CSS, it causes issues specifically in IE7, cau ...

Incorporating database row data into JavaScript objects: a guide

Here's a question that has me stumped and seeking help. Following an ajax send request, I utilized this php code to retrieve all the rows and columns from my database: $sql = "SELECT * FROM categories"; $result=$conn->query($sql); $arr = $resul ...

Implementing a sleek show/hide transition using slideToggle in jQuery

Trying to implement show/hide content with slideToggle and it's functioning, but the animation effect on the table is not smooth. Attempted two different codes, but none provided the desired animation effect: $('.more').slideToggle(' ...

Struggling to properly position my dropdown menu without causing the div content to shift downward

<div id="header"> <a href="#" id="logo"></a> </div> <div id="nav_cont"> <ul id="nav"> <li id="main_btn"><a class="mainlink" href="#">Parent 01</a></li> <li id="communities_btn">< ...

The block tag on line 8 is invalid: 'endblock'. Have you perhaps overlooked registering or loading this tag?

As a newcomer to Django, I have been learning from various Youtube tutorials. Even though I followed the steps exactly, I encountered a block tag error in my code. Here is an excerpt from my base.html template: <head> <meta charset="UTF-8"& ...

"Utilize Meteor to transmit emails to internal email addresses within the intran

I have successfully developed a Meteor App to manage requests. However, I am facing an issue where I need emails with default text to be sent whenever a request is created or updated. The challenge lies in the fact that I am operating within an intranet e ...

Yep, implementing conditional logic with the `when` keyword and radio buttons

I seem to be encountering an issue with my implementation (probably something trivial). I am utilizing React Hook Form along with Yup and attempting to establish a condition based on the selection of a radio group. The scenario is as follows: if the first ...

Transferring data from a database on Express back-end to a React front-end

I am facing an issue while trying to display user information on the front-end. Even though I can access the server using localhost:8080/api/user and see the information in the form of an empty page, my content page is unable to render this data. The code ...

How can I resolve the issue of not returning anything ondrop in my code?

Whenever I drop my div containing an image, I don't see anything. And when I try to access its ID, I get a null value. How can I extract information from a div with an image and append a row with it? For code samples or to check the codepen example, v ...

Focus on an element in ThreeJS

Is it possible to adjust the zoom direction in three.js so that it zooms towards the mouse cursor? I'm having trouble finding where to change the zoom target for this specific feature. ...

Ways to obtain every image placed onto an element

Using the img tag within div.image-block sets a background. Images can be added to .block3 through drag and drop. Is there a way to create a container that includes all elements from .image-block? <style> .image-block { position: relat ...

In JavaScript, when a condition is met, two strings are produced but only the last string is printed

My for loop with nested arrays is working fine, but it should display two strings and only shows the last one. for (i = 0; i < $scope.taskGroups.length; i++) { for (j = 0; j < $scope.taskGroups[i].tasks.length; j++) { ...

IE9 does not consider JavaScript variable as undefined

Hello, I came across this JS code written by someone else: function somename(f) var procName = ""; var procParams = new Array(); var parseEl = ""; var parseEls = new Array(); var parseInd = 0; var procParamsInd = 0; var IsVal ...

Is it possible to build a Node.js (Express) application using a combination of JavaScript and TypeScript?

Currently, I have a Node.js project (Express REST API) that is written in JavaScript. My team and I have made the decision to gradually rewrite the entire project into TypeScript. Is it possible to do this incrementally, part by part, while still being ab ...

The system seems to be having trouble locating the password property, as it is returning a value of

I'm currently working on a database project using MongoDB and Node.js. I'm trying to update a specific field, but unfortunately I keep getting an error. The model I am working with is called "ListaSalas": router.post('/updatesala', fun ...

React Router integration problem with Semantic UI React

Just diving into ReactJS and encountering a problem with using "Menu.Item" (from Semantic UI React) and React Router. I won't include my imports here, but rest assured they are all set up correctly. The constructor in my "App.jsx" looks like this: ...