user1234
user1234

Reputation: 3159

Showing a div on hover over another div is causing multiple requests to the server and flicker

I'm trying to make a div float next to another div on hover. My divs are basically like a grid, several divs placed next to each other. below is my fiddle.

http://jsfiddle.net/dfe2t1ha/3/

I'm using plain javascript and I basically want to show another div div2 floating next to div1 on hover.

ex:

<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";

    });

  });
}

but when I try to show display: block on div2 I see that its making multiple request calls to the server and its fetching the url multiple times and I see flicker on hover.I beleiev its due to the several calls it as making to the server I'm not sure exactly where the problem lies.is there a way we could fix this with css or its a js issue?

Thanks!

Upvotes: 0

Views: 60

Answers (1)

Saurabh Nemade
Saurabh Nemade

Reputation: 1582

Here is how you can do 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; //Do make sure to get it checked 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>

Link to working fiddle: https://jsfiddle.net/j05mg1xy/3/

Upvotes: 1

Related Questions