How do I avoid massive onmouseover onmouseout firing? - javascript

I have a table with some columns. In each of them is a picture where I have an onmouseover/onmouseout event on it, which shows a message in a div and hides the message.
My problem is, after a user moves quickly from left to right over a lot of images, all mouseover and mouseout events of the images are executed, which looks stupid...
Is it possible to rearrange the internal event stack to avoid this, such that the user executes only the current event (mostly the first one) and then the last one, if it is not the same type?
For example, if mouseover over first image is executed and the mouse moving position stops over an image three times next to the first one. I can avoid all other events firing, because the mouse stopped over an image and the mouseover is like the one where I stopped with the mouse.
How can I avoid this multiple event firing?

You need to check out the hoverIntent plugin, which addresses this problem.

We've had the exact same problem, What we've done is on the mouseover event is to set a variable _mouseOn to true (set to false on mouseout) then set a oneTime event over that fires in say 500 ms.. The one time event will check if the _mouseOn is true and display the image
function Hover() {
_mouseOn = true;
$(document).oneTime(500, "500ms", functionToCheckTheMouseOnAndDisplayTheImage);
};

//Global timeout handle for mouseover and mouseout
var timeoutHandle;
$(document).ready(function() {
BindMouseHover($(".helptext"));
});//closing ready
//bind mouseover and mouseout actions on all elements
function BindMouseHover(elements) {
$(elements).hover(
function() {
timeoutHandle = setTimeout('HandleMouseHover(true)', 1000);
},
function() {
HandleMouseHover(false);
}
);
}
//Handle Mouseover and mouseout events
function HandleMouseHover(bDelay) {
if (bDelay) {
$(".tooltip").show();
}
else {
$(".tooltip").hide();
clearTimeout(timeoutHandle);
}
}
Explanation:
On every mouseover schedule a call to DelayedTooltip(***true*)** after 1000ms and save the setTimeout handle to timeoutHandle
If mouseout happens within that 1000ms interval then simply call clearTimeout(***timeoutHandle*)** to cancel the setTimeout
This can be easily extended to apply to many heterogeneous elements and wire the customize tooltip text based on the element hovered.
Click here to know more about JavaScript Timing Events.

You can't, and shouldn't try to, avoid the events firing. What you should avoid is your code immediately responding to them by doing something that winds up looking stupid. For example, you can have your mouseovers register, with some controller object, which image the user is currently over, and set a short timeout to the function that triggers the actual behavior (removing a previous timeout if it's already running). The mouseout unregisters the image and removes the timeout. That way, when the behavior runs, you only operate on the image that the user moused over most recently.

I think it's better (from http://bavotasan.com/demos/fadehover/, THANKS)
<script>
$(document).ready(function(){
$(".a").hover(
function() {
$(this).stop().animate({"opacity": "0"}, "slow");
},
function() {
$(this).stop().animate({"opacity": "1"}, "slow");
});
});
</script>

Related

Fire jquery animate on same element while animation is in progress

I have 2 buttons with these code:
$('#btn1').on('click',function() {
$('#div1').animate({left:500},1000);
});
$('#btn2').on('click',function() {
$('#div1').animate({left:0},1000);
});
I want to be capable of firing the event of btn2 while btn1's event is still in progress. What is currently happening when I click both buttons fast is for example, I click btn1, the div goes and completes left:500 before actually firing btn2's event.
Any ideas?
You want to .stop() all animations before firing the new one.
You have to use the stop() function to accomplish this. Design both your event handlers like this:
$('#btn1').on('click',function() {
$('#div1').stop().animate({left:500},1000);
});
$('#btn2').on('click',function() {
$('#div1').stop()animate({left:0},1000);
});
This stops the div if currently animating and starts the new animation on it.

jQuery mobile swipe spamming and animation

I have say 5 list items with images inside placed 200px from eachother.
I am trying to animate these list items to slide horizontally left if one presses a link with the id = #next or if one swipes left. And vice versa for sliding the list items right.
Every click or swipe results in a slide animation of 200px on every list item.
I ran into a problem where spamming the #next or #prev button would cancel the current animation and start a new one. This results in list items not sliding 200px+200px+200... but something like this 200px+140px+120... This because like I said the animation is cut and therefore the sliding distance will be shorter.
Now I solved this for the clicking event by disabling the button before the animation starts and then re'enabling it on the end callbak function. But this problem is remaining for the swipe event.
How can I solve this problem for the swipe event?
If you have the code working for your click event handlers, then just .trigger() a click event on the proper element for each of the swiperight and swipeleft events:
$(document).delegate('#next', 'click.my-namespace', function () {
...
}).delegate('#prev', 'click.my-namespace', function () {
...
}).delegate('#my-page-id', 'swipeleft swiperight', function (event) {
if (event.type == 'swipeleft') {
$('#next').trigger('click.my-namespace');
} else {
$('#prev').trigger('click.my-namespace');
}
});
This way you have a single base of code that does the same thing, that gets called by multiple event handlers. I like to do this when I am adding touch events to a desktop design.
Notice I bound the event handlers with name-spaces so you don't accidentally trigger the wrong event handler.
You can also use .stop(true, true) but it may make your animations jittery when playing many in a row. The best solution when using .stop() is to always animate to an absolute value, never use +=200px, that way when you use .stop() the animation can be stopped and instantly restarted to the new absolute position: http://api.jquery.com/stop
One way you can do it is by setting a boolean variable that is global to the script with the default value of false. Then set the variable to true prior to animating and set it back to false once the animation is complete. Prior to setting off the animation, check the state of the variable, run the animation only if it's false. The code would look something like this:
var isAnimating = false;
function animate()
{
if(!isAnimating) {
//Animation code
isAnimating = false;
}
}
If the animation is asynchronous then you should set isAnimating = false in the completion function of the animation.

How to tell if a mouseup is going to be followed by a click event?

Is there any way to know, in a jQuery onmouseup handler, if the event is going to be followed by a click event for the same element?
I have an event handler for a menu hyperlink which unbinds itself when the user either clicks on an element or "drops" (as in drag-n-drop) on an element. I want to avoid prematurely unbinding the handler on mouseup if a click is coming next.
I realize I can track mousedown and mouseup events myself or otherwise hack up a solution (e.g. wait 50 msecs to see if a click comes soon), but I was hoping to avoid rolling my own implementation if there's something built-in for this purpose.
There is nothing built-in because it's really specific to your needs. Thus, there would kilometers of code and documentation to maintain if jQuery would handle any combination of clicks, long clicks, moves, etc.
It's also hard to give you a snippet that satisfies your needs, but a setTimeout is usually the first step to take, with something like that :
obj.mouseup = function (){
obj.click = action; // do action
setTimeout ( function() {
obj.click = functionOrigin // after 500 ms, disable the click interception
}, 500);
};
you can use $(selector).data('events') for that
$('div').mouseup(function(){
if($(this).data('events').click){
console.log('Has a click event handler')
}
});

Keep Jquery animation from occurring unless the event lasts n milliseconds

I thought this would do it, but it only delays the animation.
$("#searchsubmit").hover(
function () { $("#quicksearchtip").delay(100).slideDown("slow"); },
function () { $("#quicksearchtip").delay(100).slideUp("slow"); });
I don't want the event to fire if the user happens to accidentally pass the cursor over the element for a few milliseconds.
I want it to only occur when they hover over the element. It's very annoying when the cursor touches the element even for a split second the animation fires even after the mouse has left the element.
You're looking for the hoverIntent plugin.
You may ad a .stop(true) before both of the .delay() to empty the animation queue, so on quick mouse out, the delayed action will be removed.

Hover state sticks when leaving the page- ignores mouseleave

I'm using some pretty standard JavaScript/jQuery to handle hovering elements, image swaps, sliding divs, animations, etc., it does not matter. If/when clicking an "hoverable" linked element takes you to a new page, the mouseenter hover state always sticks.
For example, if you hover over something and click it (links to another page), then use the back button to return to the page, the mouseenter state on the element you clicked, is stuck even though your mouse is no longer over the element.
You have to either reload the page or re-hover the element to reset everything.
$(document).ready(function() {
$('.mySelector').each(function () {
$(this).hover(enter, leave);
});
function enter(event) {
// mouseenter stuff
};
function leave(event) {
// mouseleave stuff
};
});
I seem to remember reading about this several weeks ago and there was a very simple fix but I can no longer find that.
Is anyone familiar with a proper solution?
Thank-you!
You don't need to use .each for this. Also, the functions should be outside .ready.
$(document).ready(function() {
$('.mySelector').hover(enter, leave);
});
function enter(event) {
// mouseenter stuff
}
function leave(event) {
// mouseleave stuff
}
Edit:
If your variables are local, you could do it like this:
$(document).ready(function() {
$('.mySelector').hover(function(){
// mouseenter stuff
},
function(){
// mouseleave stuff
});
});
I ended up simply "re-setting" the hover effects by calling the mouse leave function with the window "unload"...
$(window).unload(function() {
leave();
});
Whenever you leave the page by clicking the hovered element, the mouseleave function is called even though your mouse is still hovering over the element. Hitting the browser's back button no longer takes you back to the page with a "stuck" hover effect.
Problem solved.

Categories