orph-c
orph-c

Reputation: 73

onmouseover function working, but onmouseout function is not?

right now I'm trying to make an overlay div appear when another element is hovered over, and I'm doing this with the onmouseout and onmouseover properties. In the element that is originally displayed, I have an h1 with a unique item code, and an image of the item. I also have another div that is set to display: none by default, with an id that is the code corresponding to the item. I want this div to show up on hover, and disappear when the mouse is moved away.

In the HTML code, I'm specifying functions to run on mouseover and mouseout, then in the Javascript for those functions, I'm first getting the h1 and its unique item code, then selecting the hidden div with the id as the item code to show or hide. The only difference between my show and hide functions is style.display since it is either 'block' or 'none'. The show function works perfectly, and the hidden div shows up. However, when I move my mouse out, the div isn't disappearing like its supposed to. Can someone help me figure out as to why?

function showstatus(object) {
  code = object.querySelector('h1').innerHTML;
  document.querySelector(`#${code}`).style.display = "block";
}

function normalize(object) {
  code = object.querySelector('h1').innerHTML;
  document.querySelector(`#${code}`).style.display = "none";
}
{% for listing, specs in a_dict %}
<div class="list-item" onmouseover="showstatus(this)" onmouseout="normalize(this)">
  <h1 class="hidden">{{listing}}</h1>
  <img src="image link that I didn't include" class="item-thumbnail">
</div>
{% endfor %}

Upvotes: 0

Views: 161

Answers (1)

topsoftwarepro
topsoftwarepro

Reputation: 822

Use onmouseleave instead of onmouseover as you are using it on a div.

function showstatus(object) {
    code = object.querySelector('h1').innerHTML
    document.querySelector(`#${code}`).style.display="block";
}

function normalize(object) {
    code = object.querySelector('h1').innerHTML
    document.querySelector(`#${code}`).style.display="none";
}
<div class="list-item" onmouseover="showstatus(this)" onmouseleave="normalize(this)">
       <h1 class="hidden">{{listing}}</h1>
       <img src="image link that I didn't include" class="item-thumbnail">
</div>

This is an alternate method of doing so:

document.getElementById('div').onmouseover = showstatus(document.getElementById('div'))
document.getElementById('div').onmouseout = normalize(document.getElementById('div'))

function showstatus(object) {
    code = object.querySelector('h1').innerHTML
    document.querySelector(`#${code}`).style.display="block";
}

function normalize(object) {
    code = object.querySelector('h1').innerHTML
    document.querySelector(`#${code}`).style.display="none";
}
<div id="div" class="list-item">
       <h1 class="hidden">{{listing}}</h1>
       <img src="image link that I didn't include" class="item-thumbnail">
</div>

Upvotes: 0

Related Questions