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.
Related
I wanted to add animations to my app on page enter, and hooked with the default WinJS.UI.Animation.enterPage(element), and that worked fine sliding in the element from right to left.
I need to slide it from bottom (100px) to top. Once I overrode the default values with WinJS.UI.Animation.enterPage(element, { top: "100px", left: "0px" }) I saw no animation at all on my screen which is weird.
However when coupled with WinJS.UI.Animation.exitPage(oldElement), the animation seemed to work but I wanted to further tweak the timing.
following as per https://msdn.microsoft.com/en-us/library/windows/apps/Dn127042(v=win.10).aspx#creating_custom_animations, didn't help. After using the example from "Combining custom animations and transitions" in the link, I could see only the opacity changing and the element fading in, however no translation at all. I tried the same pairing with WinJS.UI.Animation.exitPage(), and adding my own customExitPage - basically using from WinJS, and with just opacity... and nothing just works.
I was referring to some of the animation implementations from here as well -
https://github.com/winjs/winjs/blob/ad8691b3d5227ff1576a5d2a90a42f022498d2a9/src/js/WinJS/Animations.js, to get control over the timing.
Anyone else having this issue? or am I doing something wrong... or is it WinJS behaving bad?
EDIT:
weirdly enough the "to top" animation with enterPage(element, {top: "100px", left: "0px"}) started working. However the custom animation still remains elusive.
well, I was able to finally figure out the "weird behavior". The #keyframes should have been set in CSS, and I was trying a few other things and apparently that's the reason that it didn't work.
However, I would probably say the explanation could have been a little more clearer in the site as well.
when we are already providing the from - to values in the javascript, I would otherwise about providing the same again as part of CSS too which is still weird.
Like mentioned in the site,
add this to css: #keyframes custom-translate-in { from { transform: translateY(50px); } to { transform: none; } }
and have this in js:
function runCustomShowStoryboard() {
return WinJS.UI.executeAnimation(
target,
{
keyframe: "custom-translate-in",
property: "transform",
delay: 0,
duration: 367,
timing: "cubic-bezier(0.1, 0.9, 0.2, 1)",
from: "translate(50px)",
to: "none"
});
}
Never was able to figure out why and how the "bottom to top" animation started working (probably restarting visual studio helped)
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.
The problem is that I have an image larger than 477 x 205, but i'll need them for another things, it would be a problem to make 2 or 3 images with diferent sizes. So, I decided to resize it on jquery. The major problem is that i'm new on JQUERY ( please, be patient :B ).
I've read some of the topics, but none helped me, the one that got closer was to add "$('#slides').css('background-size', '477px 205px');":
$(document).ready(function() {
$('#slides').coinslider({ hoverPause: true });
$('#slides').css('background-size', '477px 205px');
$('#slides').css('overflow', 'hidden');
});
but, that didn't solve it, also, it starts at the right size, but when the slider starts looping, it gets a mess again
Change this:
$('#slides').css('background-size', '477px 205px');
To this:
$('#slides').width(477).height(205);
The overflow: hidden will hide the rest of the image.
More relevant code would be helpful in providing better guidance. Have you considered "background-size: cover" yet?
Reference 1,
Reference 2
After 1 week without the solution, i've reached on what I was making mistakes, i was o the .js, when the Js loads, he create his own CSS for the slider, so I had to add the "background-size: size" on it like this:
// positioning squares
$("#cs-"+el.id+i+j).css({
'background-position': -sLeft +'px '+(-sTop+'px'),
'left' : sLeft ,
'top': sTop,
'background-size':'477px 205px'
});
as it wasn't fixed a size to it, it would take the real size of the image as default.
Thank you for trying to help me with this issue!
I am building a Star Wars fansite.
My navigation menu will be star wars lightsabers.
I am planning to make (when the cursor is over the lightsaber) for the actual light sword to come out. When the cursor leaves the lightsaber, it goes back down.
I have a gif that does that, but how to make it unactive then active when cursor is hovered over??
If the idea above doesn't sound correct, how would you suggest I do it?
No, you can't control the animation of the images.
You would need two versions of each images, one that is animated (.gif), and one that's not(.gif/.png/.jpg/etc).
On hover you can easily change from one image to another.
Example:
$(function(){
$('img').each(function(e){
var src = $(e).attr('src');
$(e).hover(function(){
$(this).attr('src', src.replace('nonanimated.gif', 'animated.gif'));
}, function(){
$(this).attr('src', src);
});
});
});
Reference link
like Parag Meshram said, but no need to do it with jQuery or JavaScript:
.foo {
background: url(still.png) no-repeat 0 0;
}
.foo:hover {
background-image: url(animation.gif);
}
It might be a overkill, but I think you can control the GIF with WebGL.
Here is some GIF manipulation, it's not what you ask for, but maybe some inspiration for doing something own http://www.clicktorelease.com/code/gif/
Your best bet is to actually split the handle and the sword into two different graphics to then animate the sword in with Javascript (as background property). This way you wouldn't have the restrictions of the GIF file format but still a lot smaller files. You'll need to create a div the same size as the sword and set it as background, then set the background-position-x to -100% and animate it back in on hover, you can use jQuery for that:
$('.sword').on('hover', function(event){
$(this).animate({
'background-position-x': '0%',
}, 100, 'linear');
});
$('.sword').off('hover', function(event){
$(this).animate({
'background-position-x': '-100%',
}, 100, 'linear');
});
(I wrote this off the top of my head, check the jQuery docs if this doesn't work)
I had a similar situation and found a pretty simple solution. I'm pretty new to JQuery, so I'm not sure if this is in line with best practices, but it works.
I've used a static image (.png for transparency, in my case) and switched out the src attribute to point to the animated .gif on mouseenter and back to the .png on mouseleave. For your lightsaber to go from hilt alone to powering up I would do it a bit differently than usual. Try taking a frame from the .gif in Photoshop and making it into a static image using "save for web and devices". I recommend .png. In your HTML markup use this static image of the hilt for your src of the image, also be sure to give it an ID, such as saber for this example.
Now onto the jquery script. I link it in a separate file. For one saber it should look something like this:
$(document).ready(function()
{
$("#saber").mouseenter(
function()
{
$(this).attr("src", "img/stillframehilt.png");
},
function()
{
$(this).attr("src", "img/saberpowerup.gif");
});
$("#saber").mouseleave(
function()
{
$(this).attr("src", "img/saberpowerup.gif");
},
function()
{
$(this).attr("src", "img/stillframehilt.png");
});
});
Notice the on mouseleave I had it switch src to "img/saberpowerdown.gif". I think that rather than have the saber revert back instantaneously to the hilt in its dormant state (which any Star Wars geek[myself included] would wince at) it would look better to have a .gif that is essentially the reverse of the saber turning on. This can be achieved by reversing the order of the animation frames(ensure that visible layers are correct). For good measure I would make sure when to have it not loop either .gif's as well as add a few extra frames of the hilt alone when the power down is finished to ensure it remains off.
Also, it might be beneficial to add a .click to the saber to change the src to the power down, or even a different animation, but that is just extra flair. For each additional lightsaber use the same code, just changing the id to reference each in a logical way such as by color.
Again, I can't claim this to be in line with best practices as far as jquery goes (I'm but a padawan) but this method worked when I needed to activate a .gif on mouseenter and back on .mouseleave . May The Force be with you.
See the following fiddle:
[edit: updated fiddle => http://jsfiddle.net/NYZf8/5/ ]
http://jsfiddle.net/NYZf8/1/ (view in different screen sizes, so that ideally the image fits inside the %-width layouted div)
The image should start the animation from the position where it correctly appears after the animation is done.
I don't understand why the first call to setMargin() sets a negative margin even though the logged height for container div and img are the very same ones, that after the jqueryui show() call set the image where I would want it (from the start on). My guess is that somehow the image height is 0/undefined after all, even though it logs fine :?
js:
console.log('img: ' + $('img').height());
console.log('div: ' + $('div').height());
$('img').show('blind', 1500, setMargin);
function setMargin() {
var marginTop =
( $('img').closest('div').height() - $('img').height() ) / 2;
console.log('marginTop: ' + marginTop);
$('img').css('marginTop', marginTop + 'px');
}
setMargin();
Interesting problem...after playing around with your code for a while (latest update), I saw that the blind animation was not actually firing in my browser (I'm testing on Chrome, and maybe it was firing but I wasn't seeing it as the image was never hidden in the first place), so I tried moving it inside the binded load function:
$('img').bind('load', function() {
...
$(this).show('blind', 500);
});
Now that it was animating, it seemed to 'snap' or 'jump' after the animation was complete, and also seemed to appear with an incorrect margin. This smacks of jQuery not being able to correctly calculate the dimensions of something that hadn't been displayed on the screen yet. On top of that, blind seems to need more explicit dimensions to operate correctly. So therein lies the problem: how to calculate elements' rendered dimensions before they've actually appeared on the screen?
One way to do this is to fade in the element whose dimensions you're trying to calculate very slightly - not enough to see yet - do some calculations, then hide it again and prep it for the appearance animation. You can achieve this with jQuery using the fadeTo function:
$('img').bind('load', function() {
$(this).fadeTo(0, 0.01, function() {
// do calculations...
}
}
You would need to work out dimensions, apply them with the css() function, blind the image in and then reset the image styles back to their original states, all thanks to a blind animation that needs these dimensions explicitly. I would also recommend using classes in the css to help you manage things a little better. Here's a detailed working example: jsfiddle working example
Not the most elegant way of doing things, but it's a start. There are a lot more easier ways to achieve seemingly better results, and I guess I just want to know why you're looking to do image blinds and explicit alignment this way? It's just a lot more challenging achieving it with the code you used...anyways, hope this helps! :)