Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to prevent event chaining in javascript

I have 4 icons that, on mouse over, scroll a div using jquery animate.

The problem is when I hover over all four icons quickly, back and forth, the hover functions are chained together and even on mouse out, the scroll animations still run until all the mouse over events that happened, are completed.

I want to make it so on mouse out, all the events that are waiting to be executed, are cancelled!

find source below:

<div id="sidebar-slider-nav">
    <div class="testimonials" onmouseover="sidebar_slider(0)"><img src="images/icons/testimonialsIcon.png"/></div>
    <div class="facebook" onmouseover="sidebar_slider(280)"><img src="images/icons/facebookIcon.png"/></div>
    <div class="twitter" onmouseover="sidebar_slider(560)"><img src="images/icons/twitterIcon.png"/></div>
    <div class="news" onmouseover="sidebar_slider(840)"><img src="images/icons/blogIcon.png"/></div>
    <div class="clear"></div>
</div>

and the function that is called is:

function sidebar_slider(val){
    $('#sidebar-slider').animate({scrollLeft:val},500)
}

does anybody know of a better way to do this?

for an example of my problem, please navigate to http://a3mediauk.co.uk and look at the sidebar! Thankyou

like image 283
AlexMorley-Finch Avatar asked Nov 30 '11 09:11

AlexMorley-Finch


People also ask

How do I stop JavaScript from bubbling?

To stop an event from further propagation in the capturing and bubbling phases, you call the Event. stopPropation() method in the event handler. Note that the event. stopPropagation() method doesn't stop any default behaviors of the element e.g., link click, checkbox checked.

Does JavaScript support optional chaining?

Introduction to the JavaScript optional chaining operator allows you to access the value of a property located deep within a chain of objects without explicitly checking if each reference in the chain is null or undefined .

What is $() in JS?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document. getElementById("id_of_element").

What is event stopPropagation ()?

stopPropagation() The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed.


1 Answers

$('#sidebar-slider').stop();

Will clear any existing animation on the element. You can also chain this into your existing code:

$('#sidebar-slider').stop().animate({scrollLeft:val},500)
like image 67
beeglebug Avatar answered Oct 09 '22 12:10

beeglebug