Callbacks not working properly - javascript

I'm at a loss. In this code, #options should wind up fading in, but it doesn't. The CSS attributes are set, though.
$("#content > p").animate({ opacity: '0' }, function() {
$(this).css("display", "none");
$("#options").css("opacity", "0").show(0, function() {
$("#options").fadeIn();
});
});

The opacity is still being set as 0.
You can change the fadeIn() to...
$("#options").animate({ opacity: 1}, 500);
jsFiddle.

Seems like it should work, but apparently you'd need to use the fadeTo()[docs] method instead of the fadeIn()[docs] method.
$('img').css("opacity", 0).show(0,function() {
$(this).fadeTo(400, 1);
});
Although the show(0,func.. seems kinda pointless here, when you could just do:
$('img').css("opacity", 0).show().fadeTo(400, 1);
...unless the 0 you're giving for the .show() duration is actually a variable that may reference a larger number.

You can simplify your code a lot - remember setting opacity to 0 will replicate the visibility:hidden CSS attribute, whereas fadeOut() will replicate the display:none CSS attribute. The one critical difference between these two is that the latter will remove the element from rendered DOM so it will not take up space on the screen and the surrounding nodes won't even know it's there. The former will create a big empty box where the element still is but you just can't see it. Assuming you want to use the latter which is the most common, this should work:
$('#content > p').fadeOut('slow', function() {
$('#options').fadeIn();
});

Related

TweenJS javascript

My first Stackoverflow question. The tween seems to run because it calls the brute function at the end. However, there's no tween happening.
window.onload=init();
function init() {
testImg = document.getElementById("testImg");
createjs.Tween.get(testImg).wait(2000).to({alpha: 1}, 600).call(brute);
}
function brute() {
// why this function get called if there's no visible tween?
console.log("testImg alpha is " + testImg.alpha)
testImg.style.opacity=1;
}
#testImg {
opacity: .3;
background: url("http://oyos.org/oyosbtn_466x621.jpg");
}
<script src="https://code.createjs.com/tweenjs-0.6.2.min.js"></script>
<body>
<div id="testImg">
here is the div
</div>
</body>
TweenJS isn't really optimized to tween styles on HTML elements, since it was developed to tween properties directly on objects. There is a CSS plugin that can help, particularly when dealing with properties that have suffixes (like "px" on width/height, etc)
However, it can definitely be done. There are a few issues with your code:
As you mentioned in your comment above, you have to target the "opacity" instead. The alpha property is what EaselJS DisplayObjects use.
You have to target the testImg.style instead, since the opacity lives on that element, and not on the testImg directly. Setting opacity/alpha on the #testImg will do nothing
Unfortunately, TweenJS doesn't know how to read CSS properties set on elements using CSS classes or selectors. The getComputedStyle is very expensive to look up, and is required to determine what the current style of the element is.
You can totally make your demo work, but you have to consider these things. Here is an updated snippet (from this pen):
createjs.Tween.get(testImg.style) // Target the style
.to({opacity:0.3}) // Set the property initially
.wait(2000)
.to({opacity: 1}, 600)
.call(brute); // Tween the opacity instead
You could also use the change event to update the opacity yourself:
createjs.Tween.get(testImg)
.set({alpha:0}) // Still requires an initial set
.wait(2000)
.to({alpha:1})
.call(brute)
.on("change", function(event) {
// Every time the tween is updated, set the opacity
testImg.style.opacity = testImg.alpha;
});
Note that the CSS plugin I mentioned above can handle the computedStyle lookup now (a fairly recent addition).
Hope that sheds some light on the behaviour.
Cheers,

Successive background-color animation request failing with jQuery 1.6.1

I'm trying to "flash" an input box by changing the background color briefly and then reverting back to the original bg color using jquery to indicate an error and grab the users attention.
Here's a fiddle to demonstrate what I'm trying to do.
I have to use jquery version 1.6.1. In the fiddle demo, it's using 1.6.4 and the color of the input box never changes at all. Actually, it doesn't work even with 1.11. In my local tests with my code, the input box changes red with the first animation call, but fails to do anything for the second animation call (to revert the bg color back to white). It just stays red.
I'm using very similar code to do the same thing in another site, except using jquery 1.11 and it works fine.
Is this just a compatibility issue? Is there some way I can make this work properly with version 1.6.1 ?
Here's the code:
function flashInputBox(id) {
var input = $('#'+id);
input.focus();
input.stop(true).animate({'background-color': '#EC8686'}, 350, function() {
input.stop(true).animate({'background-color': '#FFFFFF'}, 1000);
});
}
I forgot to mention that I'm using jQuery UI v1.8.18
The problem is properly replicated now in this fiddle (same code, just added jQuery UI 1.8.18).
Do you need to use jQuery? If not, this is way easier in CSS using key frames. If it is, skip my CSS explanation.
CSS
This still uses jQuery, but it gives the animation job to CSS, making your code more legible. I set this up in jsFiddle if you want to check it out: jsFiddle Example
First, setup a keyframe:
#keyframes pulse{
from {
background: #ec8686;
}
to {
background: #ffffff;
}
}
#-webkit-keyframes pulse{
from {
background: #ffffff;
}
to {
background: #ec8686;
}
}
and attach it to your existing input:
#my-input{
...
-webkit-animation: pulse 5s infinite;
-webkit-animation-play-state: paused;
...
}
Then the jQuery becomes a matter of letting the animation play for a few seconds:
function doIt() {
$("#my-input").css("-webkit-animation-play-state", "running");
setTimeout(function() {
$("#my-input").css("-webkit-animation-play-state", "paused");
}, 5000);
}
Also, you don't even need the jQuery to trigger the animation. The button click can directly trigger a CSS animation, however I figured you have some sort of code to check what's in the box for accuracy, so that why I kept your old function.
Note that this keyframe ends suddenly, so you can totally have a 0%, 50%, 100% keyframe instead.
Now for the raw jQuery way:
jQuery
For your jQuery, its much easier just to either specify your input directly (aka $("#my-input-name")), or if its just one input, I got it working just by using the following code instead:
function doIt() {
...
input.stop().animate({'background-color': '#EC8686'}, 350, function() {
// just say input here //
input.animate({'background-color': '#FFFFFF'}, 1000);
});
}
Colors aren't numeric values, so they can't be animated. From the jQuery documentation for .animate, emphasis mine:
All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color() plugin is used). Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.
If you don't want to (or can't) use the jQuery.Color plugin, you'll need to animate the color "manually", e.g. by setting an interval and changing the color at each step.

Jquery mouseover & mouseout animation bug

I have a small mouseover and mouseout functionality i have to keep the mouseout function animate() instead of css() due to other reasons
the problem arises when i mouseover when the animation from opacity 1 to 0 is still going on like a quick mouseover mouseout like we do for testing.
i tried setTimeOut too so that the opacity is zeroed after required time.
both animate and setTimeOut are creating the same problem that after mouserover function updates the opacity to 1 the animate and setTimeOut are updating again to zero since they are still playing.
JSFIDDLE
Jquery Code:
$("#dp-ashish").on("mouseover",function(){
$("#dp-ashish").css("opacity","1");
});
$("#dp-ashish").on("mouseout",function(){
$("#dp-ashish").animate({"opacity":"0"},1000);
});
You might want to consider using either .stop(true, true) or .finish() (the latter only works in jQuery v1.9 and above):
$("#dp-ashish").on("mouseover",function(){
$("#dp-ashish").stop(true,true).animate({opacity:1},1000);
});
$("#dp-ashish").on("mouseout",function(){
$("#dp-ashish").stop(true,true).animate({opacity:0},1000);
});
or:
$("#dp-ashish").on("mouseover",function(){
$("#dp-ashish").finish().animate({opacity:1},1000);
});
$("#dp-ashish").on("mouseout",function(){
$("#dp-ashish").finish().animate({opacity:0},1000);
});
p/s: The opacity and its numerical integer value do not need to be wrapped in quotes. Opacity is a valid property without needing to be parsed as a string, and its accepted values are integers which do not need to be passed as a string, too.
Alternatively, you can toggle a CSS class and let CSS transitions handle the opacity change :)
http://jsfiddle.net/teddyrised/5Ekbf/4/

Animate/Slow down elements filling space left by removed element

Here is my example: http://jsfiddle.net/MT5xS/
When you click the first picture, it is removed and all the following images move back to fill the space left by it. But they move too fast and you don't even get the notion that they moved.
My question is, how do I make these elements move smoothly? Basically like an iPhone when you move or delete an icon, like this http://youtu.be/-r7K4LTbI4A?t=27s
I'm not worried about IE6/7/8 or any other compatibility issues.
The most common solution I know off is to animate hide(), then in the callback function remove your image.
$('.user-pic').live('click', function() {
var $item = $(this).closest('li');
$item.hide('slow', function(){ $item.remove(); });
});​
DEMO - Animate element removal
Take a look at this jQuery plugin: http://razorjack.net/quicksand/
It does what I think you are describing. You could use it or take a look under the covers to see how its being done. I believe they're using position: absolute on all the grid items.
Another option is to fadeTo 0, animate() the image width to 0, then remove().
http://jsfiddle.net/MT5xS/2/
Instead of removing the element on click, you want to fade the target element out and then remove the element. Note this cannot be accomplished by chaining remove after the desired animation.
If you chose to rely on old school setTimeout() you have to remember about correct variable scoping. Alternatively you could add a callback to be executed upon animation completion:
var $el = $(this).closest('li'); //no need to operate directly on img imo
$el.animate({
opacity: 0 //plus any other animation you want... height:0, width:0, ...
}, 1000, function() {
$el.remove();
});
Fiddled
I think what you want is to...
$(element).css("visibility", "hidden");
$(element).animate({"width": 0}, "slow", function() {
$(this).remove();
});
Here is the fiddle http://jsfiddle.net/MT5xS/4/
Try this it will slide up and then remove
$('.user-pic').live('click', function() {
$(this).closest('li').slideUp('slow', function() {
$(this).remove();
});
});​

jQuery animate problems

I use the following snippet to make an element's background lightblue, then slowly fade to whiite over 30 seconds:
$("#" + post.Id).css("background-color", "lightblue")
.animate({ backgroundColor: "white" }, 30000);
Two questions.
First, instead of fading to white, is there a way to fade opacity to 100%? That way I don't have to change "white" if I choose to change the page's background color?
Second, about once out of every 10 or 15 times, the background stays lightblue and fails to fade to white. I'm using the latest versions of jQuery and the UI core. What could be going wrong?
EDIT: Bounty is for a solution to problem regarding second question.
EDIT2:
Apparently I got downvoted into oblivion because I said I rolled my own solution but didn't show it. My bad. I didn't want to be self-promoting. My code works 100% of the time and doesn't require jQuery. A demonstration and the code can be found at:
http://prettycode.org/2009/07/30/fade-background-color-in-javascript/
For your second question: in my experience this is usually because a Javascript error has occurred somewhere else on the page. Once there is one Javascript exception, the rest of the page stops running Javascript. Try installing Firebug (if you haven't already), then open up the "Console" tab and enable it. Then any javascript errors or exceptions will be printed to the console.
Another thing to try (which kinda contradicts my last statement...) is to disable all your browser plug-ins to see if you can recreate. Sometimes they interfere with scripts on the page (particularly GreaseMonkey.)
If you could provide a sample HTML snippet which reproduces this animation problem it would be a lot easier for us to help you. In the script I have pasted below, I can click it all day, as fast or slow as I like, and it never fails to animate for me.
For the first question: I know you said you'd found a workaround, but the following works for me (even on IE6) so I thought I'd post it, since it may be different from what you were thinking. (Note that setting CSS "opacity" property through jQuery.css() works on IE, whereas IE does not support the "opacity" property directly in CSS.)
<html>
<head>
<style>
body { background-color: #08f; }
#test { background-color: white; width: 100px; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
var myOpacity = 0.125;
$(function(){
$('#test').css('opacity', myOpacity);
$('a').click(function(){
myOpacity = 1.0 - myOpacity;
$('#test').animate({ opacity: myOpacity });
return false;
});
});
</script>
</head>
<body>
<p>Click me</p>
<div id="test">Test</div>
</body></html>
Dont forget the color plugin.
See here
When the color fails to animate to blue you could try to use the callback function to log a message to the console. You can then check that the event actually fired and completed. If it does then you could potentially use two animates. The first one to animate to a halfway house color then the use the callback to animate to white (so you get two bites of the cherry, if the outer fails but completes the callback has a second go)
It would be good if you could try to recreate the issue or give a url of the issue itself.
e.g
$("#" + post.Id).css("background-color", "lightblue")
.animate({ backgroundColor: "#C0D9D9" }, 15000, function(){
$(this).animate({ backgroundColor: "#ffffff" }, 15000)
});
You could always use something like this, avoiding the JQuery animate method entirely.
setTimeout(function() { UpdateBackgroundColor(); }, 10);
UpdateBackgroundColor() {
// Get the element.
// Check it's current background color.
// Move it one step closer to desired goal.
if (!done) {
setTimeout(UpdateBackgroundColor, 10);
}
}
Also, you may be able to remove the "white" coding by reading the background color from the appropriate item (which may involve walking up the tree).
It is possible to have jQuery change the Opacity CSS property of an item (as mentioned in another answer), but there's two reasons why that wouldn't work for your scenario. Firstly, making something "100% opaque" is fully visible. If the item didn't have any other modifications to its opacity, the default opacity is 100%, and there would be no change, so I'm guessing you meant fading to 0% opacity, which would be disappearing. This would get rid of the light blue background, but also the text on top of it, which I don't think was your intent.
A potentially easy fix for your situation is to change the color word "white" to "transparent" in your original code listing. The color plugin may not recognize that color word (haven't checked documentation on that yet), but setting the background color to "transparent" will let whatever color behind it (page background, if nothing else) shine through, and will self-update if you change your page background.
I'll answer your first question.
You can animate opacity like this:
.animate({opacity: 1.0}, 3000)
I think you can try using fadeOut/fadeIn too..
What about:
$("#" + post.Id).fadeIn( "slow" );
You could possibly have two divs that occupy the same space (using position: absolute; and position: relative; setting the z-index on one higher to make sure one is above and the other is below. the top one would have a transparent background and the one below would have a background color. then just fadeout the one below.
As for the second question:
If you think the default animation classes from JQuery are not properly working you could try Bernie's Better Animation Class. I have some good experiences with that library.
Animate only works for numbers. See the jquery docs. You can do opacity but you can't do background color. You can use the color plug in. Background-color uses strings like 'red', 'blue', '#493054' etc... which are not numbers.

Categories