On hover

this is my html:

<ul> <li>Milk</li> <li>Bread</li> <li class='fade'>Chips</li> <li class='fade'>Socks</li> </ul> 

this is my js function: -

 $("li").hover( function () { $(this).append($("<span> ***</span>")); }, function () { $(this).find("span:last").remove(); } ); 

I want this type of output: -

 <ul> <li>Milk</li> <li>Bread</li> <li class='fade'>Chips</li> <li class='fade'>Socks</li> <span> ***</span> </ul> 

here i am trying to add one range in mouseover on li.
his work is beautiful.
but I want to add only once after the last li.
thanks.

+4
source share
4 answers

I found an example in the jQuery api manual , is this not what you want?

 $("li").hover( function () { $(this).append($("<span> ***</span>")); }, function () { $(this).find("span:last").remove(); } ); 

Or you don’t want to delete the range when the mouse leaves, and just want to add one range:

 $("li").hover(function () { if ($(this).find('span').length == 0) { $(this).append($("<span> ***</span>")); } }); 
+2
source

Use one :

 $("li").one("hover", function () { $(this).append($("<span> ***</span>")); }); 

http://api.jquery.com/one/

+1
source

Just check first if the range already exists. Remember that “freezing” can perform two functions if you want to delete a range after leaving the mouse. This is equivalent to combining a mouse and a mouse.

 $("li").hover( function () { if ($(this).is(':empty')) { $(this).append($("<span> ***</span>")); } }); 

Links: hover , empty , mouseover , mouseleave

0
source

Use modern JS!

 const lis = document.getElementsByTagName("li"); let span; for (const li of lis) { li.addEventListener("mouseover", function() { // Do something cool if (!span) { span = document.createElement("span"); span.innerText = " ***"; li.parentElement.append(span); } }, {once : true}); // (optional) This will make it fire only once for each li // You could add one "once" listener to just the ul as well } 

Documentation , CanIUse

0
source

All Articles