.hover on element to make div appear

I have some container divs with span inside and I want to make a content div appear when over a span.
Then it must remain visible if I remain on the container div or on the content div itself.
This is what I tried but it does not work well…

https://jsfiddle.net/pbomL8zw/11/

Hi @varievincenzo, there are a few things to note:

  • jQuery(".divCont").mouseenter() should be mouseleave()
  • divPub.hover( function(e) { _keepDiv(e) } , _hideDiv ) should be on the same level as the above line – otherwise you’re binding a new additional event listener each time you’re showing the div
  • The showed variable isn’t used anywhere
  • The condition inside _hideDiv will prevent hiding the div in most cases; as far as I can tell, you might drop it altogether (and then you don’t need the divParentId variable either)

Together it might look like this:

function _showDiv () {
  let elPos = this.parentNode.getBoundingClientRect()
  let divPub = jQuery('#divPub')

  divPub.css('top', elPos.top)
  divPub.css('left', elPos.right)
  divPub.show()
}

function _keepDiv () {
  jQuery('#divPub').show()
}

function _hideDiv (event) {
  jQuery('#divPub').hide()
}

jQuery('.Pover').mouseenter(_showDiv)
jQuery('.divCont').mouseleave(_hideDiv)
jQuery('#divPub').hide().hover(_keepDiv, _hideDiv)

fiddle

Thank you m3g4p0p.
It’s quite right but there’s a problem: if I leave the content div, it disappear. This is ok if I move the mouse out of the original container div, but I would like to let the content div still visible if I return on the original container div.
In my example, if you move the mouse from the content div to the original div it remains visible: ok, but if you move it on the other container div, the content div correctly disappears. The problem was it’s not disappearing if I move directly on the blank area.
What I want:

  1. content div must be visible:
  • if I’m on content div
  • if I move mouse from the content div to the original container div
  1. content div must return hidden:
  • if I leave the content div overing every element BUT the original container div

Ah yes, sorry I missed that. I think the easiest solution would then be to move the content div inside the container div on hover; this way, you’re not actually leaving the container when moving the mouse to the content div, and no mouseleave event will get triggered:

const $divPub = $('#divPub')

$('.pover').mouseenter(function () {
  $divPub.appendTo(this.parentElement).show()
})

$('.divCont').mouseleave(function () {
  $divPub.hide()
})

As an additional advantage, the positioning can be done using CSS only by giving the container a position: relative – here’s an updated fiddle.

2 Likes

Perfect!
Also very neat, short code. Thank you.

2 Likes

Glad I could help. :-)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.