Teja Reddy Teja Reddy - 6 months ago 45
jQuery Question

Jquery mouse enter and mouse leave not working on li element

I am trying to use jquery mouse enter and mouse leave functions .
this is my code :
html :

<ul class="menuList bold">
<li id="tevee">
<span>test</span>
</li>
</ul>


jquery

$(function(){
$(".tevee").on("mouseenter",".menuList",hoverInFunction());

$(".tevee").mouseleave(hoverOutFunction("tevee"));

});

function hoverInFunction()
{
alert("hi")
}

function hoverOutFunction(variable)
{
alert("test");
}


https://jsfiddle.net/tejareddy/dndvsudh/ . this is my fiddle , they are not working instead they are triggering on page load and not every time when i hover on them .

Answer

Firstly, your selector was incorrect for the ".on" call, secondly, you were using parenthesis when referring to a function (which in this case must be referred to as an object without the parenthesis).

$(function(){
    $(".menuList").on("mouseenter","li",hoverInFunction);

    $(".menuList").on("mouseleave","li",hoverOutFunction);

})

Please see the fixed version here

You may use event.data if you wish to pass parameters into the calls.

The original method of binding the event to the ID is not what .on is all about, it's best to bind to a higher-level object in the DOM (such as the actual menuList) and then write a selector which will affect the children on it. That way you get "delegated eventing" and any dynamically added items will still work the way you want them to.

Comments