if width == 200px run function - javascript

Here is a jsFiddle showing the problem
I'm not sure why this doesn't work:
if ($('#menu').width() == '200px') {
alert("what");
}
I want an alert to appear when the animation is completed. So I assumed that I could say that since when the animation is done the element has a width of 200px, it would show the alert.

1) You're checking for the value before the animation completes.
2) You width value will be "200" not "200px"
Here is the jQuery documentation. You need to perform your check in the callback section of the code.
$('#clickme').click(function() {
$('#book').animate({
opacity: 0.25,
left: '+=50',
height: 'toggle'
}, 5000, function() {
// Animation complete. <---- your value check code goes here
});
});

jQuery.width returns a number. You are comparing with a string.

Check the updated fiddle. What I did was added a 'callback' function, which executes whenever the animation is complete.
$(this).stop().animate({ width: "200px" }, 250,
function(){if ($('#menu').width() == '200') { alert("what"); } /* Callback Function */
});

.width() should return a number, not a "###px" value, Try if ($('#menu').width() == 200) {.

Related

jQuery returns the same opacity

I am trying to use simple animation with opacity css property:
$('#testAnimation').click(function (event) {
if ($(this).css('opacity') == 0) {
$('#animationTarget').animate({opacity: 1}, 'slow');
} else {
$('#animationTarget').animate({opacity: 0}, 'slow');
}
});
The first time, element is successfully hidden. But when I click button second time, $(this).css('opacity') returns value "1".
Debugging in browser clearly says that opacity is 0.
Can someone explain this behavior?
You are checking the opacity of this and changing the one of the #animationTarget.
This should do it:
$('#testAnimation').click(function (event) {
if ($('#animationTarget').css('opacity') == 0) {
$('#animationTarget').animate({opacity: 1}, 'slow');
} else {
$('#animationTarget').animate({opacity: 0}, 'slow');
}
});
Well, this was my fault.
For anyone who faces similar issue, be sure that you are checking property of the desired element:
if ($(this).css('opacity') == 0)
Should be replaced with:
if ($('#animationTarget').css('opacity') == 0)
Try using .fadeIn() and .fadeOut() to achieve what you are doing.
Less code to write. have a look at the :visible part as I don't remember if it is the correct syntax!
$('#testAnimation').click(function (event) {
if ($(this).is(':visible') {
$(this).fadeOut();
} else {
$(this).fadeIn();
}
});
Checking for $(this) within your click event handler you will refer to the element $('#testAnimation')
Instead you should check for $('#animationTarget') and also you can refactor your code like this:
$('#testAnimation').on('click', function (event) {
var $animationTarget = $('#animationTarget'),
opacity = $animationTarget.css('opacity') == 0 ? 1 : 0;
$animationTarget.animate({opacity: opacity}, 'slow');
});

jQuery animation setup callback throws error

I want to implement a jQuery animation callback method progress or step,
but in either case I'm getting the following error:
NS_ERROR_IN_PROGRESS: Component returned failure code: 0x804b000f (NS_ERROR_IN_PROGRESS) [nsICacheEntry.dataSize]
I searched a lot but not able to find anything in context, I am kind of stuck here, please suggest what could cause this error?
In fiddle i tried with step and progress and its working there , but not able to get it worked in my code, I am just looking, has some one faced such kind of error in jquery animation?
The sample code is:
this.taskHandle.find('img').stop(true, true).animate({
//todo//
top: vtop, // this.taskHandle.outerHeight(),
//'top': 0 - $('.target.upper').height(),
width: 0,
opacity: 0
}, {
duration: 2000,
step: function(){
console.log('I am called');
}
},
$.proxy(function() {
// some css clearing method
}, {
// some further actions after animation completes
})
);
You have some semantic errors going on here. I'm going to repost your code, formatted for easier reading:
this.taskHandle.find('img')
.stop(true, true)
.animate(
{
//todo//
top: vtop , // this.taskHandle.outerHeight(),
//'top' : 0 - $('.target.upper').height(),
width : 0,
opacity : 0
},
{
duration:2000,
step: function() {
console.log('I am called');
}
},
$.proxy(
function() {
// some css clearing method
},
{
// some further actions after animation completes
}
)
);
First: animate() doesn't accept 3 parameters (at least not those 3 parameters). I'm not sure what you are trying to do with your css clearing method, but anything you wan't to happen after the animation is complete should be in the complete method that you add right next to the step method.
Second: $.proxy() needs to have the context in which you want it to run as the second parameter, not some other"complete"-function.
So here is a slightly modified example which works. You can try it yourself in this fiddle.
var vtop = 100;
$('div')
.stop(true, true)
.animate(
{
top: vtop,
width: 0,
opacity : 0
},
{
duration: 2000,
step: function() {
console.log('I am called');
},
complete: function () {
alert('complete');// some further actions after animation completes
}
}
);
You could use Julian Shapiro's Velocity.js, which animations are (arguable) faster than jQuery and CSS (read this for more)
It allows you to use callbacks such as :
begin
progress
complete
like :
var vtop = 100;
jQuery(document).ready(function ($) {
$('div').find("img").velocity({
top: vtop,
width: 0,
opacity: 0
}, {
duration: 2000,
begin: function (elements) {
console.log('begin');
},
progress: function (elements, percentComplete, timeRemaining, timeStart) {
$("#log").html("<p>Progress: " + (percentComplete * 100) + "% - " + timeRemaining + "ms remaining!</p>");
},
complete: function (elements) {
// some further actions after animation completes
console.log('completed');
$.proxy( ... ); // some css clearing method
}
});
}); // ready
Notice that you just need to replace .animate() by .velocity()
See JSFIDDLE

Submenu animation "pops up"

I have a menu with sub items inside it. In order to make animation effect I want, I need to retrieve sub-menu width,height and height of its first-child. Now my animation works ,but sometimes my sub-menu just "pops up" (it doesn't animate its width ).
Here is The Fiddle of the problem.
http://www.vasinternetposao.com/wordpressdevelopment/wp-content/themes/override/images/submenu_problem.png
I am using this code:
var j = jQuery.noConflict();
j(document).ready(function () {
j('ul.nav').removeClass('nav').addClass('jnav'); //Add jquery Class to our menu
j('ul.jnav li').hover(function () {
if (j(this).children('ul:first').hasClass('jsub-menu')) { //Let's check if "jsub-menu" Class is here
return false; //If it is ("jsub-menu" here) don't SlideDown...
} else { //Else slide down if no class
j(this).find('ul.sub-menu:first').not(':animated').slideDown(500);
}
}, function () {
j(this).find('ul:first').slideUp(500, function () {
j(this).removeClass('jsub-menu').addClass('sub-menu');
j(this).css({
'height': '',
'width': ''
});
});
});
j('ul.jnav ul.sub-menu a').hover(function () {
j(this).addClass('active');
if (j('.active').next('ul.sub-menu').length) { //If submenu exist...
j('.active').next('ul.sub-menu').css({
'visibility': 'hidden',
'opacity': '0',
'display': 'block'
}); //Show it so we can read its:
var get_width = j('.active').next('ul.sub-menu').outerWidth(true); //WIDTH
var get_height_of_first_child = j('.active').next('ul.sub-menu').children('li:first').outerHeight(true); //HEIGHT of its First Child
var get_submenu_height = j('.active').next('ul.sub-menu').outerHeight(true); //HEIGHT of our menu
j('.active').next('ul').removeClass('sub-menu') //Remove class from menu, add another class apply HEIGHT of FIRST CHILD and hide it again...
.addClass('jsub-menu').css({
'visibility': '',
'opacity': '',
'height': get_height_of_first_child + 'px',
'width': '0'
});
j('.active').next('.jsub-menu').animate({
width: get_width
}, 1000, function () { //Animate WIDTH
j('.active').next('.jsub-menu').animate({
height: get_submenu_height
}, 1000); //callback animate HEIGHT
});
} //End if
}, function () {
j('.active').removeClass('active');
});
});
I think that this is happening because my Slide Up/Down animations are conflicting with my animate with/height functions but I am not sure. I have tried to solve it by adding stop(),stop(true,true),stop(true,false) in numerous combinations but failed. I am trying to solve this for days now so you stackers are my only hope. Please help!
Thank you!!
I was finally able to replicate the error.
I wrote this code for you, to replace the code you have for the animation.
var animating = false;
function animate($elm, options, callback) {
if (animating)
return;
animating = true;
$elm.animate(options, 1000, function() {
animating = false;
if (callback != undefined)
callback();
});
}
Call it like this, from inside your hover callback.
animate(j('.active').next('.jsub-menu'),
{
'width': get_width,
'height' : get_submenu_height
});
Basically, it checks if another animation is already running, in which case it doesn't start it. The Flag is set to false when the animation stopped, and let's other animations go on.
You can also pass a callback to do something after the animation is completed, but in your case you don't need it, because you can animate the height and width in the same time.
I tested it for like a minute and it looked pretty smooth.
Here is the updated feedle: http://jsfiddle.net/gabrielcatalin/TNxJ4/1/
P.S. You may also want to use the $ sign instead of 'j' for jQuery wrappers.

jquery .animate callback executing automatically

$(function(){
$("#obj").click(function(){
$("#theimage").animate({height: '334px', width: '500px'},function(){
$("#obj").click(function(){
$("#theimage").animate({height: '150px', width: '250px' })
});
});
});
});
the first animate makes the image 500x334 and the callback is supposed to execute once you click the image again which will make it small, however the callback is executing automatically (i think this is supposed to happen) but I was wondering if there was a way to stop it from executing and then when you click the image it will then animate again? When i added a .stop it worked once and then after that it kept executing twice?
The problem is you are registering a click handler within another one, so when the second click happens your first and second will get triggered
$(function () {
var flag = false;
$("#obj").click(function () {
if (flag) {
$("#theimage").stop(true, true).animate({
height: '150px',
width: '250px'
})
} else {
$("#theimage").stop(true, true).animate({
height: '334px',
width: '500px'
});
}
flag = !flag;
});
});
Actually callbacks are made for executing a set of code after an animation or a particular job completed. So whenever the first animation got executed completely, obviously the call back part should get executed. Try like this,
$(function(){
$("#obj").click(function(){
if (parseInt($("#theimage").width()) === 500)
{
$("#theimage").stop().animate({height: '150px', width: '250px' })
}
else
{
$("#theimage").stop().animate({height: '334px', width: '500px'});
}
});
});
LIVE - DEMO

jquery small error

i am very new at jquery and code, here i am trying to get the setTimeout event to be inside the .mouseout event but i'm not sure how to do that as i keep getting syntax error in my editor. Here's what i have:
jQuery(document).ready(function() {
$('.slidedown').hide();
$('.trigger').hover( function(){ // enter animation
$('.slidedown').stop(true,true).animate({
height: ['toggle', 'swing'],
}, 600, function() { /* animation done */ });
}, function(){ // leave animation
$('.slidedown').mouseout()
setTimeout( function(){
$('.slidedown').stop(true,true).animate({
height: '0px',
}, 600, function() { /* animation done */ });
}, 1000 );
});
});
A small nuance, in this code the user mouses over a div, then another div bellow it slides down. Moving the mouse to the .slidedown div should keep it open until the mouse is removed. But will this code collapse the .slidedown div if the user doesn't mouse over .slidedown after .trigger but instead moves the mouse directly from .trigger to another area of page? I.e i need some kind of 'setTimeout' that is trigged only if the user doesn't move mouse over .slidedown after hovering over .trigger. Hope i make sense. Thanks for your help!
This line is the problem
$('.slidedown').mouseout()
It shoule be
$('.slidedown').mouseout( YOUR_CALLBACK_FUNCTION )
You should pass a callback function which will act as an event handler and inside that event handler you can call setTimeout() the way you have done it.
So the correct code would look like this
$('.slidedown').mouseout( function() {
setTimeout( function(){
$('.slidedown').stop(true,true).animate( {
height: '0px',
},
600,
function() { /* animation done */ }
); // animate ends here
}, 1000 ); // setTimeout ends here
}); // mouseout ends here
Thanks T.J and Arnab, this works:
$(document).ready(function() {
$('.slidedown').hide();
$('.trigger').hover( function(){ // enter animation
$('.slidedown').stop(true,true).animate({
height: ['toggle', 'swing'],
}, 600, function() { /* animation done */ });
}, function(){ // leave animation
$('.slidedown').mouseout( function() {
setTimeout( function(){
$('.slidedown').stop(true,true).animate( {
height: '0px',
},
600,
function() { /* animation done */ }
); // animate ends here
}, 1000 ); // setTimeout ends here
}); // mouseout ends here
});
});
But the other thing i mentioned about moving the mouse over .trigger but then away (but not into .slidedown) doesn't work. The .slidedown just remains open. :) :( I think it will be very complex to get a .mouseout event that has a kind of 'allow' rule for one destination of the mouse.

Categories

Resources