jQuery delay doesn't work as expected - javascript

I have the following jQuery code
$("#dropdown").hover(function() {
$(this).stop(true,true).fadeTo('fast',1);
$("#options").stop(true,true).slideDown();
}, function() {
$(this).delay(1000).stop(true,true).fadeTo('fast',0.1);
$("#options").delay(1000).stop(true,true).slideUp();
}
);
What I expect to happen is when the mouse leaves #dropdown it will wait 1 second before continuing. This is not happening.
What I am trying to achieve, in case there is a better way, is to leave the drop down menu visible for a second or two after moving your mouse and I would also like to prevent the events from happening again to prevent artifacts and "funnies" if you were to move the mouse over and out from the div very quickly

The problem is .stop(). If you take that out it works:
http://jsfiddle.net/LZ8yt/

Your calls to stop aren't placed on the animation queue - they run immediately. I'm not sure whether you really need them in the "hover out" routine.
edit removed dumbness

You can always go lo-tech with setTimeout.
var dropDownElement = $(this);
setTimeout(function()
{
dropDownElement.fadeTo('fast', 0.1);
// Other Code
}, 1000);

Related

Button that displays and hides a sliding menu

I'm trying to build a header with a menu button that triggers a sliding menu. I can make the menu appear when I press the button, but I also want it to dissappear when I click the button again.
This is the event that triggers when the button is clicked.
$('#nav-button').click(function () {
$("#slidermenu").animate({right: "0px"}, 200);
$("body").animate({right: "300px"}, 200);
});
I looked up the animate method and saw that it has a function called done, which takes two parameters. A promise and a boolean. So I figured I can use a if-statement to check if the animation is done, and if the animation is done, the button would send the slidermenu back.
But how can I test if animate().done() is true? Or is there a more simple way of achiveing this?
Here is my fiddle.
.is(':animated') will return true if it's currently being animated.
In the context of what you're trying to do:
if(!$('#slidermenu').is(':animated'))
{
// Animation has finished
}
As an aside:
I try and do this with CSS only now where possible. If you use jQuery toggleClass and predefine the right attributes in your CSS for the toggled classes, you can add a CSS transition to deal with the animation. Just thought it was worth mentioning (this does come with it's own compatibility issues).
Like DeeMac said, it may be better to do this with css transition instead of jQuery animate. But just to add an option, I'll try to show you how to get this to work with jQuery animation also.
First of all, instead of inspecting if the animation is still running or not, you can just stop the ongoing animation before starting another. It will make the button to respond immediately to the users clicks.
For finding out if the menu is open or not, you can use toggleClass. This way you can just use hasClass to determine in which direction you need to animate the menu.
So, this what I came up with:
$('#nav-button').click(function () {
$("#slidermenu").stop();
animateToPosition = "0px";
if ($("#slidermenu").hasClass("open")) {
animateToPosition = "-300px";
}
$("#slidermenu").toggleClass("open");
$("#slidermenu").animate({
right: animateToPosition
}, 200);
});
I made a Demo. If you are going with the css solution, it's fine. Maybe this will help someone else in the future.

Jquery bug dblclick/click

I've been experimenting with jquery and have come upon a problem. http://javascript.nicklewers.co.uk/nav/
On the 'Android' tab I've set it so that if you click once, the sub menu will appear, however when doubleclicking, the main content will appear.
Now the problem is: a double click involves two single clicks which involves the sub menu opening and closing very quickly and this looks bad. How do I prevent this?
try this (using a timer to know if single click or double):
alreadyclicked=false;
$('#android').bind('click',function(){
var el=$(this);
if (alreadyclicked)
{
alreadyclicked=false; // reset
clearTimeout(alreadyclickedTimeout); // prevent this from happening
// do what needs to happen on double click.
}
else
{
alreadyclicked=true;
alreadyclickedTimeout=setTimeout(function(){
alreadyclicked=false; // reset when it happens
// do what needs to happen on single click.
// use el instead of $(this) because $(this) is
// no longer the element
},300); // <-- dblclick tolerance here
}
return false;
});
Try a delay before showing/hiding the submenu. With JS this can be done using the setTimeout() function.
$('#android').dblclick(function(){
$('.content, #subnav').toggle();
});
why do you toggle both the content and the submenu? Removing it is not going to solve the problem, but I think it should not be there.

check for ('div')mouseenter on ('a')mouseleave

my problem is following:
I got a trigger(a) and a popup(div). The div doesn't lie nested inside the anchor.
When I hover over a, I want the div to show up.
When I go from a to the div, I want it to stay visible.
When I leave the div, I want it to close.
When I hover over a and leave without entering the div, I want the div to close.
I got most of that figured out, but now I'm struggeling with requierement no. 2.
When checking for mouseleave on a, I check if there is a mouseenter on the div. If it is, I want to abort the mouseleave. If not, I want to close the div.
What am I doing wrong? Is this even the right way to do this?
Here's the markup:
<a href="#" class="popup_toggle" style='display:block;width:50px;height:50px;border:1px solid red;position:relative;'>Toggle</a>
<div class="popup_div" style='position:absolute;top:50px;left:0px;border:1px solid blue;display:none;'>Popup</div>
Here's the jQuery:
$('.popup_toggle').mouseenter(function() {
var element = $(this).next('.popup_div');
$.data(this, 'timer', setTimeout(function() {
element.show(100);
}, 500));
});
$('.popup_toggle').mouseleave(function() {
clearTimeout($.data(this, 'timer'));
if($('.popup_div').mouseenter==true)
{
return false;
}
else
{
$('.popup_div').hide(100)
};
});
What you're trying to do is fairly simple. When entering the trigger, identify the panel (layer, popup, whatever), save reference to each other using .data() and have the event handlers check if the related targets are either the trigger (from the panel view) or the panel (from the trigger view). I threw something together. Have a look at the console log to see how this works… http://jsfiddle.net/rodneyrehm/X5uRD/
That will most likely not work...no. I would suggest that you add a mouseenter and mouseleave callback to you <div> element as well and have them set a global variable that tells your other callbacks how to handle their events, i.e. "if global variable is true, don't hide the popup on mouseleave, otherwise hide popup" or something like this.
The other approach would be to check whether the mouse is inside the popup when the mouseleave callback tries to hide the popup. That might be much more work than it is worth though.
I believe the problem with your implementation is that the mouseenter on the div will fire shortly after the mouseleave from the a.
This would give you something like:
$('.popup_toggle').mouseenter(function() {
// Clear any pending "hide" timer
// Set a show timer
});
$('.popup_toggle').mouseleave(function() {
// Clear any pending "show" timer
// Set a hide timer
});
$('.popup_div').mouseenter(function() {
// Clear any pending "hide" timer
});
Note that you'll have to make sure that you access the same timer from both the .popup_toggle event and the .popup_div event. You may want to consider using Ben Alman's doTimeout plugin to help with this. It (usually) results in much clearer code than manually working with setTimeout/clearTimeout.

Prevent Javascript from being executed twice

I have a script that I am developing that creates a sliding button type effect. Five div's are situated next to eachother each with a link. When one of those DIVS are clicked on the associated content is expanded and the rest of the Div's are closed.
The problem is, if a user clicks the Div twice while it loads or clicks another Div in rapid succession, cracks start to show.
I am wondering if it would be possible to only allow the query to be executed once and wait until completion rather than queuing it.
Here is my current code, if it is crap feel free to comment on how I could better it... I am not the best at Javascript/jQuery :P
function mnuClick(x){
//Reset all elements
if($('#'+x).width()!=369){
$('.menu .menu_Graphic').fadeOut(300);
$('.menu_left .menu_Graphic').fadeOut(300);
$('.menu_right .menu_Graphic').fadeOut(300);
$('.menu').animate({width: "76px"},500);
$('.menu_left').animate({width: "76px"},500);
$('.menu_right').animate({width: "76px"},500);
}
var ElementId = '#' + x;
$(ElementId).animate({
width: 369 + "px"
},500, function(){
$(ElementId + ' .menu_Graphic').fadeIn(300);
});
}
Thanks in advance,
Chris.
You need a "isRunning" flag. Check for it before you start. Set it when you start the sequence, clear it when it ends.
(function() {
var mutex = false;
function mnuClick(x){
if (!mutex) {
mutex = !mutex;
/* all code here ... */
mutex = !mutex; /* this statement should go into animation callback */
}
}
})();
mantain a state through a variable so you cannot click more than once until code has fully executed
you can unplug the onClick event handler (mnuClick) when the event starts, to effectively disable invoking the mnuClick twice, but be sure to restore it when the event ends.
Quick answer: use .addClass and .removeClass and test for the existence of the class at execution time. Test if it's set and return, or add it, execute the code, then remove it.
you can create an invisible maskin and maskout ( like the background in lightbox etc ) or disable clicks until the animation finishes.

jquery buffer/queue for effects? Or to tell if an effect is in process?

I have a click event that checks to see if a form is correct i.e. filled out details.. and then i call a function that does this
$('#message_text').html(text);
$('#message_system').fadeIn("slow");
$('#message_system').animate({ opacity: 1.0 }, 5000)
.fadeOut('slow', function() {
$(this).hide();
});
All works ok, as long as i wait .. if i double click the button twice for example that it stops displaying ...
I presume if it is hidden hide() then fadeIn() will automatically show it?
Anyone got any experience with this ??
What i probably would like to do is on the second click then disgard current effects and redisplay new messaage
THanks
I'm not sure if this is what you're after, but have you looked at the stop() method.
You can skip straight to the end of any current animations by calling $('#message_system').stop(true, true) before beginning again.
if ( ! $(this).is(':animated') ) {
// Do the animation...
}

Categories

Resources