jQuery callback freezing up - javascript

I made a little fiddle to illustrate the problem.
Basiaclly this works:
var visible = $('#container').find(' > div:visible'),
hidden = $('#container').find(' > div:hidden');
visible.fadeOut(1000, function() {
});
setTimeout(function() { hidden.fadeIn('slow') },1000);
and this doesn't:
var visible = $('#container').find(' > div:visible'),
hidden = $('#container').find(' > div:hidden');
visible.fadeOut(1000, function() {
hidden.fadeIn(100)
});
The second way makes the page freeze up.
Is there something wrong with the way I'm using the callback?
I need to be able to put it in an animation queue, because I need to be able to stop() everything.
Is there any way to make this work? I's broken on Chrome and FF

The problem in your 2nd solution is, that an animation will be started for each visible div and for each animation (which has finished) all hidden divs start the fade in animation.

Uhh, first of all, why are you using such construction:
$('#container').find(' > div:visible');
Just use:
$('#container > div:visible');
Second, don't use #container because for some reason if fires fadeOut for 301 elements inside which is just too much.
Scratch that, i see jsfiddle has been changed and now it's only one element in there. Not surprised that it crashed before - too many objects.
Third, after fadeOut nothing fades in because at the point when you assign hidden variable there is no hidden divs. You'll have to use this in your callback:
$('#container2 > div:hidden').fadeIn(1000)

Related

jQuery UI Slide - Move content during animation

I'm building a website which relies on jQuery effects and I have a problem with the jQuery Slide effect.
I'm using that through a toggle function for the moment, but that will change in a later stage.
The fact is that I'm hinding an element when a certain action is executed. When you use the function slide the content beneath those elements moves when the animation is completed to take up the free space which was created with the effect.
The problem is that the content is only moved as soon as the animation is completed. Is there any way to move the content when the animation is still running. With other words, I want to move the content together with the animation, but I don't want to call the slide function on my element that should move with it.
I've created a JSFiddle to demonstrate the problem: http://jsfiddle.net/6Lg9vL8m/6/
Edit: Question update and fiddle
Here's an update to the question, and please see my original updated fiddle.
When you execute the slide effect in jQuery UI, see the bottom example on my fiddle, the box is moved up, and is somewhere placed behind an invisible screen (tough to explain).
With the animate function, see the top example in my fiddle, the area is shrinked, and that's something which I want to avoid. I want to achieve the effect such as 'Slide' does, but the content under the box must move up immediately with the animation, and not after the animation has been completed.
Edit: Reworked the correct answer in a plugin.
Thanks to the answers I've received here, I found the correct code, modified a bit, and created a plugin from it which I'll place here.
The plugin is called 'Curtain' and can be described as rising the requested element as a curtain and thus move it out of the way.
Here's the source code:
(function($) {
$.fn.curtain = function(options, callback) {
var settings = $.extend( {}, $.fn.curtain.defaults, options);
var tabContentsHeight = $(this).height();
$(this).animate({height:0}, settings.duration);
$(this).children().animate({'margin-top':'-' + tabContentsHeight + 'px'}, settings.duration, function() {
$(this).css({"margin-top":0});
if ($.isFunction(callback)) {
callback(this);
}
});
return this; // Allows chaining.
};
$.fn.curtain.defaults = {
duration: 250
};
}(jQuery));
The plugin can be called like this:
element.curtain({ duration: 250 }, function() {
// Callback function goes here.
});
If someone has remarks or a better way to solve this problem, please share it in the comments.
You can do it by using the animate function like this:
$('#square').on('mousedown', function(e) {
$(this).animate({height:-200},2500);
});
Demo
Updated code to create a "curtain raising" like animation:-
$('#square').on('mousedown', function(e) {
$(this).animate({height:-200},2500);
$(this).children().animate({"margin-top":"-400px"},2500, function() {
$(this).css({"margin-top":0})
});
});
CSS:
`#square{
overflow:hidden;
}`
Demo 2
This is the effect you wanted?
$('#square').on('click', function(e) {
$(this).animate({height :0},2500 );
});

Changing the order of events in Jquery

So I created some pop-up code that will contain specific information from each link clicked in the pop-up. When closed, the content in the pop-up div gets deleted. Here is my code:
var $content = $('#popupcontent');
var $window = $('#popupwindow');
$('.open').click(function(){
//alert('runnning');
var a = $(this).contents('span');
$content.append(a);
$window.fadeIn(300);
});
$('.close').click(function(){
//alert('running');
var a = $content.contents('span');
$window.fadeOut(300);
$('#popupcontent span').remove();
});
My issue is that it is somehow removing the content before fading out, so the viewer can then see that the pop-up container goes blank. How can I make it so that it will surely fade out first and then remove the content? Here is a Jsfiddle to illustrate that: http://jsfiddle.net/kAdQK/4/
You may want to utilize the complete call back argument for the fadeout method, to remove the element once fadeout is completed. With your current code it will start the fadeout animation and then immediately remove the content without waiting for fadeout animation to complete, hence you get the visual effect that you are seeing now. Using the callback you make sure that it gets executed once the animation is complete.
$window.fadeOut(300, function () {
$('#popupcontent span').remove();
});
Syntax
.fadeOut( [duration ] [, complete ] )
Fiddle
You can use the animation complete to remove your element after the fadeout ends.
The following code will ensure that #popupcontent is removed only after it's faded out
$window.fadeOut('slow', function() {
$('#popupcontent span').remove();
});
Just use a setTimeout();
$window.fadeOut(300);
setTimeout(function(){
$('#popupcontent span').remove();},2000);
Example Here

Trigger event on animation complete (no control over animation)

I've a scenario that requires me to detect animation stop of a periodically animated element and trigger a function. I've no control over the element's animation. The animation can be dynamic so I can't use clever setTimeout.
Long Story
The simplified form of the problem is that I'm using a third party jQuery sliding banners plugin that uses some obfuscated JavaScript to slide banners in and out. I'm in need of figuring out a hook on slideComplete sort of event, but all I have is an element id. Take this jsfiddle as an example and imagine that the javascript has been obfuscated. I need to trigger a function when the red box reaches the extremes and stops.
I'm aware of the :animated pseudo selector but I think it will need me to constantly poll the required element. I've gone through this, this, and this, but no avail. I've checked jquery promise but I couldn't figure out to use that in this scenario. This SO question is closest to my requirements but it has no answers.
P.S. Some more information that might be helpful:
The element isn't created by JavaScript, it is present on page load.
I've control over when to apply the plugin (that makes it periodically sliding banner) on the element
Most of the slideshow plugins I have used use changing classes at the end of the animation... You could extend the "addClass" method of jQuery to allow you to capture the class change as long as the plugin you use is using that method like it should:
(function($){
$.each(["addClass","removeClass"],function(i,methodname){
var oldmethod = $.fn[methodname];
$.fn[methodname] = function(){
oldmethod.apply( this, arguments );
this.trigger(methodname+"change");
return this;
}
});
})(jQuery);
I threw together a fiddle here
Even with obfuscated code you should be able to use this method to check how they are sending in the arguments to animate (I use the "options" object when I send arguments to animate usually) and wrap their callback function in an anonymous function that triggers an event...
like this fiddle
Here is the relevant block of script:
(function($){
$.each(["animate"],function(i,methodname){
var oldmethod = $.fn[methodname];
$.fn[methodname] = function(){
var args=arguments;
that=this;
var oldcall=args[2];
args[2]=function(){
oldcall();
console.log("slideFinish");
}
oldmethod.apply( this, args );
return this;
}
});
})(jQuery);
Well since you didn't give any indication as to what kind of animation is being done, I'm going to assume that its a horizontal/vertical translation, although I think this could be applied to other effects as well. Because I don't know how the animation is being accomplished, a setInterval evaluation would be the only way I can guess at how to do this.
var prevPos = 0;
var isAnimating = setInterval(function(){
if($(YOUROBJECT).css('top') == prevPos){
//logic here
}
else{
prevPos = $(YOUROBJECT).css('top');
}
},500);
That will evaluate the vertical position of the object every .5 seconds, and if the current vertical position is equal to the one taken .5 seconds ago, it will assume that animation has stopped and you can execute some code.
edit --
just noticed your jsfiddle had a horizontal translation, so the code for your jsfiddle is here http://jsfiddle.net/wZbNA/3/

hide() vs hide("slow")

I need to hide a div and, with this code it works fine:
var idObj = $(this).attr('key');
var valH = $(this).attr('hideval');
var valS = $(this).attr('showval');
if ($('div[name='+idObj+']').attr('isdisplay') == 'no') {
$('div[name='+idObj+']').children().show("slow");
$('div[name='+idObj+']').attr('isdisplay','yes');
var divTitle = $('div[name='+idObj+']').children().first();
var divArrow = $(this).children().first();
//.attr('src',prefixImg+valH);
//divTitle.show();
//divArrow.show();
$(this).children().first().attr('src',prefixImg+valH);
} else {
var divTitle = $('div[name='+idObj+']').children().first();
var divArrow = $('div[name='+idObj+']').children().last();
//.attr('src',prefixImg+valS);
$('div[name='+idObj+']').children().hide();
$('div[name='+idObj+']').attr('isdisplay','no');
divTitle.show();
divArrow.show();
$(this).children().first().attr('src',prefixImg+valS);
}
My div is hidden and the Title and arrows to reopen the div are shown. But if I try to use hide("slow") the divTitle and divArrow don't appear when my div is closed. Same problem using hide(1000).
Is there a difference between hide with and without "slow" parameter?
thanks,
Andrea
From the official site
The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.
When a duration is provided, .hide() becomes an animation method. The .hide() method animates the width, height, and opacity of the matched elements simultaneously. When these properties reach 0, the display style property is set to none to ensure that the element no longer affects the layout of the page.
So, if hide is used without delay, it hides immediately without animating - eg, poof.
If it's used with time, it becomes animated, so it disapears over time.
For your problems, it is difficult to judge without the corresponding html code.
$(element).hide() hides an element instantly, where $(element).hide('slow') will animate its disappearance (slowly).
It looks like (though I'm not sure) you want to do stuff after the animation is finished. In that case, do something like this:
var that = this; // here to preserve scope for the block below
$('div[name='+idObj+']').children().hide('slow', function() {
// This stuff happens after the hide animation is done.
$('div[name='+idObj+']').attr('isdisplay','no');
divTitle.show();
divArrow.show();
$(that).children().first().attr('src',prefixImg+valS); // <= note "that" instead of "this"
});
According to the jQuery documentation
The strings 'fast' and 'slow' can be supplied to indicate durations of
200 and 600 milliseconds, respectively.
Also duration in milliseconds can be supplied to it..

Breaking loop when user clicks on a new tab - jQuery Tabs

I am working on some tabbed navigation for my website and I have an issue I'd like to fix.
I've been scrambling my head all day and getting nowhere. Would really appreciate some help.
Here be the code: http://jsfiddle.net/EghAt/
1) Notice when you click Tab 1 and then immediately click Tab 2, Tab 1 continues to loop out all the results.
I would prefer if this stopped looping Tab 1 results and just started looping Tab 2 results.
Is this possible?
How do I achieve this?
Many thanks for any pointers
You can stop the previous animation in this function of yours, by adding the .stop(true, true) you see in this revised function:
function fadeOutItems(ele, delay) {
var $$ = $(ele), $n = $$.next();
// Toggle the active class
$$.toggleClass('active');
// Ensure the next element exists and has the correct nodeType
// of an unordered list aka "UL"
if ($n.length && $n[0].nodeName === 'UL') {
$('li', $n).each(function(i) {
// Determine whether to use a fade effect or a very quick
// sliding effect
delay ? $(this).stop(true, true).delay(i * 400).fadeToggle('slow') : $(this).stop(true, true).slideToggle('fast');
});
}
}
Since you call this on both the currently active tab and the newly active tab, this should stop any animations underway on the currently active tab.
See the jQuery doc on .stop() for details.
In looking at this code further, I believe it does what you literally asked for in your question (it stops the previous tab looping and starts the next tab), but I'm not sure that's actually what you want because it leaves the items in a tab only partially expanded. If that's what you want, then this will do that.
If that's not what you want, then the code will have to be modified a bit further to not only stop the currently running animations, but to put all the items for the old tab into the same state.
As I suspected, you actually want more than you asked for (per your most recent comments). You want the previously items to be hidden, no matter what state they were in previously. You can do that with this code where I changed the slideToggle() to a slideUp(). You can't use any form of toggle if the animation hasn't started yet because toggle will go the wrong way (it just reverses the state). Instead, when hiding you have to use a definitive animation that ends with the item not visible. You can use this code where I used slideUp() but you could pick something different if you wanted:
// A helper function that allows multiple LI elements to be either
// faded in or out or slide toggled up and down
function fadeOutItems(ele, show) {
var $$ = $(ele), $n = $$.next();
// Toggle the active class
$$.toggleClass('active');
// Ensure the next element exists and has the correct nodeType
// of an unordered list aka "UL"
if ($n.length && $n[0].nodeName === 'UL') {
$('li', $n).each(function(i) {
// Determine whether to use a fade effect or a very quick
// sliding effect
show ? $(this).stop(true, true).delay(i * 400).fadeToggle('slow') : $(this).stop(true, true).slideUp('fast');
});
}
}
You can see that in action here: http://jsfiddle.net/jfriend00/rzd3N/.
The problem is here.
$(this).delay(i * 400).fadeToggle('slow')
You are giving a fede effect to each element at once, by increasing delay.
It's not easy to stop it this way. The correct way to do this is to call a function which will only fade an element at a time. Then this function will be executed again at a given time interval (400 in your case), and fade the next element.
This way, passing a variable to the function, for example stopExecuting=true, will stop the effects.
Take a look at setInterval and setTimeout to achieve this.

Categories