I'm trying to add a popup to an existing ul (#top-menu-nav) in a tool with jquery. The only thing I'm struggling with is how to add the condition to only close the dropdown when the user is not hovering the li-item ($elementLi) or the popup (.popup-links) and keep it open as long the user is hovering over one of these two elements. In other words; How can I add the condition the popup closes when the cursor leaves the li-item or the popup area, whatever is first. Currently the popup only closes when the cursor moves over the popup-area and leaves it. Thank you for your help.
HTML given by the tool - not editable
<ul id="top-menu-nav">
<li>Ex1</li>
<li >
<a href="/index.php?r=custom_pages/view&id=26" target="" data-sort-order="800"><i ></i> Links</a>
</li>
<li>Ex2</li>
</ul>
HTML
<div >
<ul >
<p style="font-weight: 700; padding-top: 20px;">Social Media</p>
<li><a href="">LinkedIn</a></li>
<li><a href="">Instagram</a></li>
<li><a href="">Vimeo</a></li>
</ul>
</div>
Jquery
$(function() {
$elementA = $('#top-menu-nav').find('a:contains("Links")');
$elementLi = $elementA.closest('li');
$elementLiPos = $elementLi.position();
$($elementLi).mouseover(function() {
var pos = $(this).position();
var width = $(this).outerWidth();
$('.popup-links').css({
position: "fixed",
top: pos.top "px",
left: (pos.left width) "px"
}).show();
});
$('.popup-links').on('mouseleave', function(){
$(this).hide();
});
});
CodePudding user response:
you need to add mousemove event on body to check whether mouse is hovering onto the menu-item or the dropdown in order to show hide
$('body').on('mousemove',(e)=>{
if(!e.target.closest('li') && !e.target.closest('.popup-links') ) $('.popup-links').hide()
})
CodePudding user response:
easiest way without changing much code is to first hide the popup when the page loads that means add
$('.popup-links').hide();
like
$(function() {
//here
$('.popup-links').hide();
$elementA = $('#top-menu-nav').find('a:contains("Links")');
$elementLi = $elementA.closest('li');
$elementLiPos = $elementLi.position();
$($elementLi).mouseover(function() {
var pos = $(this).position();
var width = $(this).outerWidth();
$('.popup-links').css({
position: "fixed",
top: pos.top "px",
left: (pos.left width) "px"
}).show();
});
$('.popup-links').on('mouseleave', function(){
$(this).hide();
});
});