JavaScript animation - javascript
I am trying to animate a div moving 200px horizontally in JavaScript.
The code below makes it jump the pixels, but is there a way to make it look animated without using jQuery?
function () {
var div = document.getElementById('challengeOneImageJavascript');
div.style.left = "200px";
}
Here is a basic animation setup:
function animate(elem,style,unit,from,to,time) {
if( !elem) return;
var start = new Date().getTime(),
timer = setInterval(function() {
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+unit;
if( step == 1) clearInterval(timer);
},25);
elem.style[style] = from+unit;
}
To use:
animate(
document.getElementById('challengeOneImageJavascript'),
"left","px",0,200,1000
);
This example will animate the given element to slide linearly from 0px to 200px over a time of 1 second (1000 ms).
You can easily do this through CSS3-Transition :
#challengeOneImageJavascript {
-webkit-transition: left .2s;
-moz-transition: left .2s;
-o-transition: left .2s;
transition: left .2s;
}
Though, it is not supported by IE9 and earlier browser versions.
I did a ton of research, and I finally learned how to do it really well.
I like to place my program in a window.onload function, that way it dosn't run the code until the page has finished loading.
To do the animation, make a function(I'll call it the draw function) and call it what ever you want except reserved words, then at the very end of the draw function call the requestAnimationFrame function and give it the name of the function to be called next frame.
Before the requestAnimationFrame function can be used it must be declared.
See the code below:
window.onload = function() {
function draw() { // declare animation function
context.fillStyle = "white";
context.fillRect(0, 0, 400, 400);
requestAnimationFrame(draw); // make another frame
}
var requestAnimationFrame = // declare the
window.requestAnimationFrame || // requestAnimationFrame
window.mozRequestAnimationFrame || // function
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
draw(); // call draw function
}
Note: Nothing after the line that calls the draw function will run, so you need to put everything you want to run before the line that calls the draw function.
You would have to use a javascript timeout function, and change the css value a little at a time. The easiest way would be to increment by a set amount each time until a threshold is reached, which would give you a linear animation, which would look clunky and amateurish compared to jQuery's default swing animation which follows a bezier curve approximately like an s-curve.
Untested code should do the linear animation
var lefty = 0;
var animate = function(){
lefty += 20;
var div = document.getElementById('challengeOneImageJavascript');
div.style.left = lefty +"px";
if(lefty < 200)
setTimeout(animate(),100);
}
animate()
n.b. there are lots of improvements to make to that block of code, but it should get you going...
With JavaScript, you will have to use setInterval function or this is how it can be done in jQuery:
$('#challengeOneImageJavascript').animate({left: '=-5'});
Adust value (5) as per your needs as well as direction via =- or =+
With Vanilla JavaScript:
var interval;
var animate = function(id, direction, value, end, speed){
var div = document.getElementById(id);
interval = setInterval(function() {
if (+(div.style) === end) {
clearInterval(interval);
return false;
}
div.style[direction] += value; // or -= as per your needs
}, speed);
}
And you can use it like:
animate('challengeOneImageJavascript', 'left', 5, 500, 200);
To stop animation any time, you would do:
clearInterval(interval);
Note: This just a very quick way to do it to give you an idea.
Simplest way via css.
https://jsfiddle.net/pablodarde/5hc6x3r4/
translate3d uses hardware acceleration running on GPU.
http://blog.teamtreehouse.com/increase-your-sites-performance-with-hardware-accelerated-css
HTML
<div class="movingBox"></div>
CSS
.movingBox {
width: 100px;
height: 40px;
background: #999;
transform: translate3d(0,0,0);
transition: all 0.5s;
}
.moving {
transform: translate3d(200px,0,0);
background: #f00;
}
JavaScript
const box = document.getElementsByClassName('movingBox')[0];
setTimeout(() => {
box.className += ' moving';
}, 1000);
CustomAnimation is a small libary for animating html elements which is written in pure js.You can use this libary.
Related
Any way to update the duration of an animation set via element.animate without restarting the animation?
I'm developing a game engine in HTML5. Characters are div elements using an animated sprite for background. As sprite animation have fluid parameters and must be set by code, they can't be predefined in a static CSS definition, thus I use element.animate to set sprite animations to a given row at a given speed knowing my scales and frame counts. // Applies the given frame and animation to the sprite // Frame is an angle, clockwise direction: 0 = up, 1 = right, 2 = down, 3 = left set_animation(frame, duration) { const scale_x = this.settings.sprite.scale_x * this.settings.sprite.frames_x; const pos_y = this.settings.sprite.scale_y * -frame; // Cancel the existing animation if(this.data_actors_self.anim) { this.data_actors_self.anim.cancel(); this.data_actors_self.anim = null; } // Play the animation for this row or show the first frame if static if(duration > 0) { this.data_actors_self.anim = this.element.animate([ { backgroundPosition: px([0, pos_y]) }, { backgroundPosition: px([scale_x, pos_y]) } ], { duration: duration * 1000, direction: "normal", easing: "steps(" + this.settings.sprite.frames_x + ")", iterations: Infinity }); this.data_actors_self.anim.play(); } else { this.element.style.backgroundPosition = px([0, pos_y]); } } Obviously that's a snippet from an actor class function: this.element is the div, this.settings is an object with parameters to be used who's names should make sense in this context, the px() function is a simple converter to turn arrays into pixel strings for HTML (eg: [0, 0] to "0px 0px"). The issue I'm having: While I can always run this function to set a new animation, I want the ability to change the speed of the animation without resetting it. It doesn't need to be a smooth transition, for all I care the new speed can be applied at the next iteration... I only want to avoid a visual snap or any kind of reset upon applying the change. Once an animation is set, I have no idea how to access and update its duration parameter. Does anyone have any suggestions? When using console.log on this.data.anim I'm rightfully told it's an animation object. I tried using JSON.stringify to get more information but nothing relevant is printed. this.data.anim.duration returns undefined so the setting must be stored under some other property. Even if I know that property, I'd like to be sure web browsers will agree with me changing it like this.data.anim.options.duration = new_duration.
You can wait for the end of an iteration before changing the animation duration if that is what is required. This snippet only sets an event listener for animationiteration event when you click the button to increase the speed. function upthespeed() { const div = document.querySelector('div'); div.addEventListener('animationiteration', function() { div.style.animationDuration = '1s'; }); document.querySelector('button').style.display = 'none'; } div { width: 10vmin; height: 10vmin; background-color: magenta; animation: move 10s linear infinite; } #keyframes move { 0% { transform: translateX(50vw); } 50% { transform: translateX(0); } 100% { transform: translateX(50vw); } } <div></div> <button onclick="upthespeed()">Click me to increase the speed at the end of the next iteration (you may have to wait!)</button>
The value for the animation duration isn't in the Animation object itself but in the CSS animation-duration property for the Element: so this.data_actors_self.style.animationDuration = new_duration will do the job. It will however restart the animation if it is being played, but if I understand correctly that isn't a problem for you. Edit: To change the animation's duration without restarting it, all you have to do is set the value of anim.startTime to what it was before. For example: const startTime = anim.startTime; this.data_actors_self.style.animationDuration = new_duration anim.startTime = startTime;
requestAnimationFrame animation loop
I have the following code snippet: function animate() { testdiv.style.transitionDuration="2500ms" testdiv.style.transitionTimingFunction="linear" testdiv.style.transform="rotate(45deg)" window.requestAnimationFrame(animate) } window.requestAnimationFrame(animate) This rotates the div 45 degrees and is working. How can I turn this into an infinite animation loop so that the animation restarts automatically (from 0 degrees)?
It doesn't make sense to use requestAnimationFrame for either your current code, or the code you want to change to. For the current code, you're setting a style and then letting CSS take over. There's no need to do anything after time has passed. To change it to reset and repeat the loop, you want to trigger the new code when the animation has finished, not when the browser is ready to render a new frame. To do that, listen for the transitionend event and then remove the transform value to set it back to the default. var testdiv = document.querySelector("div"); testdiv.addEventListener("transitionend", animate); setTimeout(animate, 100); function animate() { if (testdiv.style.transform) { testdiv.style.transform = ""; } else { testdiv.style.transform = "rotate(45deg)"; } } body { padding: 100px; } div { transition-Duration: 2500ms; transition-Timing-Function: linear; } <div>....</div>
Hi try with below code. var FPS = 24; //Frame per second. var prevTime,curTime; function animate() { curTime = new Date(); if(prevTime === undefined || (curTime - prevTime) >= 1000/FPS) { testdiv.style.transitionDuration="2500ms" testdiv.style.transitionTimingFunction="linear" testdiv.style.transform="rotate(45deg)" prevTime = curTime; } window.requestAnimationFrame(animate); } window.requestAnimationFrame(animate)
Flashing text on value change [duplicate]
I'm brand new to jQuery and have some experience using Prototype. In Prototype, there is a method to "flash" an element — ie. briefly highlight it in another color and have it fade back to normal so that the user's eye is drawn to it. Is there such a method in jQuery? I see fadeIn, fadeOut, and animate, but I don't see anything like "flash". Perhaps one of these three can be used with appropriate inputs?
My way is .fadein, .fadeout .fadein, .fadeout ...... $("#someElement").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100); function go1() { $("#demo1").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100)} function go2() { $('#demo2').delay(100).fadeOut().fadeIn('slow') } #demo1, #demo2 { text-align: center; font-family: Helvetica; background: IndianRed; height: 50px; line-height: 50px; width: 150px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="go1()">Click Me</button> <div id='demo1'>My Element</div> <br> <button onclick="go2()">Click Me</button> (from comment) <div id='demo2'>My Element</div>
You can use the jQuery Color plugin. For example, to draw attention to all the divs on your page, you could use the following code: $("div").stop().css("background-color", "#FFFF9C") .animate({ backgroundColor: "#FFFFFF"}, 1500); Edit - New and improved The following uses the same technique as above, but it has the added benefits of: parameterized highlight color and duration retaining original background color, instead of assuming that it is white being an extension of jQuery, so you can use it on any object Extend the jQuery Object: var notLocked = true; $.fn.animateHighlight = function(highlightColor, duration) { var highlightBg = highlightColor || "#FFFF9C"; var animateMs = duration || 1500; var originalBg = this.css("backgroundColor"); if (notLocked) { notLocked = false; this.stop().css("background-color", highlightBg) .animate({backgroundColor: originalBg}, animateMs); setTimeout( function() { notLocked = true; }, animateMs); } }; Usage example: $("div").animateHighlight("#dd0000", 1000);
You can use css3 animations to flash an element .flash { -moz-animation: flash 1s ease-out; -moz-animation-iteration-count: 1; -webkit-animation: flash 1s ease-out; -webkit-animation-iteration-count: 1; -ms-animation: flash 1s ease-out; -ms-animation-iteration-count: 1; } #keyframes flash { 0% { background-color: transparent; } 50% { background-color: #fbf8b2; } 100% { background-color: transparent; } } #-webkit-keyframes flash { 0% { background-color: transparent; } 50% { background-color: #fbf8b2; } 100% { background-color: transparent; } } #-moz-keyframes flash { 0% { background-color: transparent; } 50% { background-color: #fbf8b2; } 100% { background-color: transparent; } } #-ms-keyframes flash { 0% { background-color: transparent; } 50% { background-color: #fbf8b2; } 100% { background-color: transparent; } } And you jQuery to add the class jQuery(selector).addClass("flash");
After 5 years... (And no additional plugin needed) This one "pulses" it to the color you want (e.g. white) by putting a div background color behind it, and then fading the object out and in again. HTML object (e.g. button): <div style="background: #fff;"> <input type="submit" class="element" value="Whatever" /> </div> jQuery (vanilla, no other plugins): $('.element').fadeTo(100, 0.3, function() { $(this).fadeTo(500, 1.0); }); element - class name first number in fadeTo() - milliseconds for the transition second number in fadeTo() - opacity of the object after fade/unfade You may check this out in the lower right corner of this webpage: https://single.majlovesreg.one/v1/ Edit (willsteel) no duplicated selector by using $(this) and tweaked values to acutally perform a flash (as the OP requested).
You could use the highlight effect in jQuery UI to achieve the same, I guess.
If you're using jQueryUI, there is pulsate function in UI/Effects $("div").click(function () { $(this).effect("pulsate", { times:3 }, 2000); }); http://docs.jquery.com/UI/Effects/Pulsate
$('#district').css({opacity: 0}); $('#district').animate({opacity: 1}, 700 );
Pure jQuery solution. (no jquery-ui/animate/color needed.) If all you want is that yellow "flash" effect without loading jquery color: var flash = function(elements) { var opacity = 100; var color = "255, 255, 20" // has to be in this format since we use rgba var interval = setInterval(function() { opacity -= 3; if (opacity <= 0) clearInterval(interval); $(elements).css({background: "rgba("+color+", "+opacity/100+")"}); }, 30) }; Above script simply does 1s yellow fadeout, perfect for letting the user know the element was was updated or something similar. Usage: flash($('#your-element'))
You could use this plugin (put it in a js file and use it via script-tag) http://plugins.jquery.com/project/color And then use something like this: jQuery.fn.flash = function( color, duration ) { var current = this.css( 'color' ); this.animate( { color: 'rgb(' + color + ')' }, duration / 2 ); this.animate( { color: current }, duration / 2 ); } This adds a 'flash' method to all jQuery objects: $( '#importantElement' ).flash( '255,0,0', 1000 );
You can extend Desheng Li's method further by allowing an iterations count to do multiple flashes like so: // Extend jquery with flashing for elements $.fn.flash = function(duration, iterations) { duration = duration || 1000; // Default to 1 second iterations = iterations || 1; // Default to 1 iteration var iterationDuration = Math.floor(duration / iterations); for (var i = 0; i < iterations; i++) { this.fadeOut(iterationDuration).fadeIn(iterationDuration); } return this; } Then you can call the method with a time and number of flashes: $("#someElementId").flash(1000, 4); // Flash 4 times over a period of 1 second
How about a really simple answer? $('selector').fadeTo('fast',0).fadeTo('fast',1).fadeTo('fast',0).fadeTo('fast',1) Blinks twice...that's all folks!
I can't believe this isn't on this question yet. All you gotta do: ("#someElement").show('highlight',{color: '#C8FB5E'},'fast'); This does exactly what you want it to do, is super easy, works for both show() and hide() methods.
This may be a more up-to-date answer, and is shorter, as things have been consolidated somewhat since this post. Requires jquery-ui-effect-highlight. $("div").click(function () { $(this).effect("highlight", {}, 3000); }); http://docs.jquery.com/UI/Effects/Highlight
function pulse() { $('.blink').fadeIn(300).fadeOut(500); } setInterval(pulse, 1000);
I was looking for a solution to this problem but without relying on jQuery UI. This is what I came up with and it works for me (no plugins, just Javascript and jQuery); -- Heres the working fiddle -- http://jsfiddle.net/CriddleCraddle/yYcaY/2/ Set the current CSS parameter in your CSS file as normal css, and create a new class that just handles the parameter to change i.e. background-color, and set it to '!important' to override the default behavior. like this... .button_flash { background-color: #8DABFF !important; }//This is the color to change to. Then just use the function below and pass in the DOM element as a string, an integer for the number of times you would want the flash to occur, the class you want to change to, and an integer for delay. Note: If you pass in an even number for the 'times' variable, you will end up with the class you started with, and if you pass an odd number you will end up with the toggled class. Both are useful for different things. I use the 'i' to change the delay time, or they would all fire at the same time and the effect would be lost. function flashIt(element, times, klass, delay){ for (var i=0; i < times; i++){ setTimeout(function(){ $(element).toggleClass(klass); }, delay + (300 * i)); }; }; //Then run the following code with either another delay to delay the original start, or // without another delay. I have provided both options below. //without a start delay just call flashIt('.info_status button', 10, 'button_flash', 500) //with a start delay just call setTimeout(function(){ flashIt('.info_status button', 10, 'button_flash', 500) }, 4700); // Just change the 4700 above to your liking for the start delay. In this case, //I need about five seconds before the flash started.
Would a pulse effect(offline) JQuery plugin be appropriate for what you are looking for ? You can add a duration for limiting the pulse effect in time. As mentioned by J-P in the comments, there is now his updated pulse plugin. See his GitHub repo. And here is a demo.
Found this many moons later but if anyone cares, it seems like this is a nice way to get something to flash permanently: $( "#someDiv" ).hide(); setInterval(function(){ $( "#someDiv" ).fadeIn(1000).fadeOut(1000); },0)
The following codes work for me. Define two fade-in and fade-out functions and put them in each other's callback. var fIn = function() { $(this).fadeIn(300, fOut); }; var fOut = function() { $(this).fadeOut(300, fIn); }; $('#element').fadeOut(300, fIn); The following controls the times of flashes: var count = 3; var fIn = function() { $(this).fadeIn(300, fOut); }; var fOut = function() { if (--count > 0) $(this).fadeOut(300, fIn); }; $('#element').fadeOut(300, fIn);
If including a library is overkill here is a solution that is guaranteed to work. $('div').click(function() { $(this).css('background-color','#FFFFCC'); setTimeout(function() { $(this).fadeOut('slow').fadeIn('slow'); } , 1000); setTimeout(function() { $(this).css('background-color','#FFFFFF'); } , 1000); }); Setup event trigger Set the background color of block element Inside setTimeout use fadeOut and fadeIn to create a little animation effect. Inside second setTimeout reset default background color Tested in a few browsers and it works nicely.
Like fadein / fadeout you could use animate css / delay $(this).stop(true, true).animate({opacity: 0.1}, 100).delay(100).animate({opacity: 1}, 100).animate({opacity: 0.1}, 100).delay(100).animate({opacity: 1}, 100); Simple and flexible
$("#someElement").fadeTo(3000, 0.3 ).fadeTo(3000, 1).fadeTo(3000, 0.3 ).fadeTo(3000, 1); 3000 is 3 seconds From opacity 1 it is faded to 0.3, then to 1 and so on. You can stack more of these. Only jQuery is needed. :)
There is a workaround for the animate background bug. This gist includes an example of a simple highlight method and its use. /* BEGIN jquery color */ (function(jQuery){jQuery.each(['backgroundColor','borderBottomColor','borderLeftColor','borderRightColor','borderTopColor','color','outlineColor'],function(i,attr){jQuery.fx.step[attr]=function(fx){if(!fx.colorInit){fx.start=getColor(fx.elem,attr);fx.end=getRGB(fx.end);fx.colorInit=true;} fx.elem.style[attr]="rgb("+[Math.max(Math.min(parseInt((fx.pos*(fx.end[0]-fx.start[0]))+fx.start[0]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[1]-fx.start[1]))+fx.start[1]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[2]-fx.start[2]))+fx.start[2]),255),0)].join(",")+")";}});function getRGB(color){var result;if(color&&color.constructor==Array&&color.length==3) return color;if(result=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)) return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];if(result=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)) return[parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];if(result=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)) return[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16)];if(result=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)) return[parseInt(result[1]+result[1],16),parseInt(result[2]+result[2],16),parseInt(result[3]+result[3],16)];if(result=/rgba\(0, 0, 0, 0\)/.exec(color)) return colors['transparent'];return colors[jQuery.trim(color).toLowerCase()];} function getColor(elem,attr){var color;do{color=jQuery.curCSS(elem,attr);if(color!=''&&color!='transparent'||jQuery.nodeName(elem,"body")) break;attr="backgroundColor";}while(elem=elem.parentNode);return getRGB(color);};var colors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]};})(jQuery); /* END jquery color */ /* BEGIN highlight */ jQuery(function() { $.fn.highlight = function(options) { options = (options) ? options : {start_color:"#ff0",end_color:"#fff",delay:1500}; $(this).each(function() { $(this).stop().css({"background-color":options.start_color}).animate({"background-color":options.end_color},options.delay); }); } }); /* END highlight */ /* BEGIN highlight example */ $(".some-elements").highlight(); /* END highlight example */ https://gist.github.com/1068231
Unfortunately the top answer requires JQuery UI. http://api.jquery.com/animate/ Here is a vanilla JQuery solution http://jsfiddle.net/EfKBg/ JS var flash = "<div class='flash'></div>"; $(".hello").prepend(flash); $('.flash').show().fadeOut('slow'); CSS .flash { background-color: yellow; display: none; position: absolute; width: 100%; height: 100%; } HTML <div class="hello">Hello World!</div>
Here's a slightly improved version of colbeerhey's solution. I added a return statement so that, in true jQuery form, we chain events after calling the animation. I've also added the arguments to clear the queue and jump to the end of an animation. // Adds a highlight effect $.fn.animateHighlight = function(highlightColor, duration) { var highlightBg = highlightColor || "#FFFF9C"; var animateMs = duration || 1500; this.stop(true,true); var originalBg = this.css("backgroundColor"); return this.css("background-color", highlightBg).animate({backgroundColor: originalBg}, animateMs); };
This one will pulsate an element's background color until a mouseover event is triggered $.fn.pulseNotify = function(color, duration) { var This = $(this); console.log(This); var pulseColor = color || "#337"; var pulseTime = duration || 3000; var origBg = This.css("background-color"); var stop = false; This.bind('mouseover.flashPulse', function() { stop = true; This.stop(); This.unbind('mouseover.flashPulse'); This.css('background-color', origBg); }) function loop() { console.log(This); if( !stop ) { This.animate({backgroundColor: pulseColor}, pulseTime/3, function(){ This.animate({backgroundColor: origBg}, (pulseTime/3)*2, 'easeInCirc', loop); }); } } loop(); return This; }
Put this together from all of the above - an easy solution for flashing an element and return to the original bgcolour... $.fn.flash = function (highlightColor, duration, iterations) { var highlightBg = highlightColor || "#FFFF9C"; var animateMs = duration || 1500; var originalBg = this.css('backgroundColor'); var flashString = 'this'; for (var i = 0; i < iterations; i++) { flashString = flashString + '.animate({ backgroundColor: highlightBg }, animateMs).animate({ backgroundColor: originalBg }, animateMs)'; } eval(flashString); } Use like this: $('<some element>').flash('#ffffc0', 1000, 3); Hope this helps!
Here's a solution that uses a mix of jQuery and CSS3 animations. http://jsfiddle.net/padfv0u9/2/ Essentially you start by changing the color to your "flash" color, and then use a CSS3 animation to let the color fade out. You need to change the transition duration in order for the initial "flash" to be faster than the fade. $(element).removeClass("transition-duration-medium"); $(element).addClass("transition-duration-instant"); $(element).addClass("ko-flash"); setTimeout(function () { $(element).removeClass("transition-duration-instant"); $(element).addClass("transition-duration-medium"); $(element).removeClass("ko-flash"); }, 500); Where the CSS classes are as follows. .ko-flash { background-color: yellow; } .transition-duration-instant { -webkit-transition-duration: 0s; -moz-transition-duration: 0s; -o-transition-duration: 0s; transition-duration: 0s; } .transition-duration-medium { -webkit-transition-duration: 1s; -moz-transition-duration: 1s; -o-transition-duration: 1s; transition-duration: 1s; }
just give elem.fadeOut(10).fadeIn(10);
This is generic enough that you can write whatever code you like to animate. You can even decrease the delay from 300ms to 33ms and fade colors, etc. // Flash linked to hash. var hash = location.hash.substr(1); if (hash) { hash = $("#" + hash); var color = hash.css("color"), count = 1; function hashFade () { if (++count < 7) setTimeout(hashFade, 300); hash.css("color", count % 2 ? color : "red"); } hashFade(); }
you can use jquery Pulsate plugin to force to focus the attention on any html element with control over speed and repeatation and color. JQuery.pulsate() * with Demos sample initializer: $(".pulse4").pulsate({speed:2500}) $(".CommandBox button:visible").pulsate({ color: "#f00", speed: 200, reach: 85, repeat: 15 })
Loop and interval hybrid in javascript?
I wrote some JQuery and JS to power a single message element that: reads a new message from an array for each loop starts off-screen, animates right, to center screen for 1/4 of the loop duration waits at the center to be read for 1/2 of the loop duration animates right again, off screen for another fourth of the loop duration changes to the next loop with a new message repeats And what sounds like a simple task became (in relation to the feature) many lines of code: function flow(i, duration){ var message = Game.activities[i] var transTime = duration / 4; var idleTime = duration / 2; var windowDouble = $(window).width() * 2; $(".message-flow").text(message); $(".message-flow") .animate({transform:"translateX(-" + windowDouble + "px)"},0) .animate({transform:"translateX(0px)"},transTime) .delay(idleTime) .animate({transform:"translateX(" + windowDouble + "px)"},transTime); } function flowFunc(i, duration){ return function(){ flow(i, duration); } } function activityFlowInit(duration){ var delay = 0; for (var i = 0; i < Game.activities.length; i++){ setTimeout(flowFunc(i, duration),delay); delay += duration; } totalDuration = duration * Game.activities.length; setTimeout(function(){ activityFlowInit(duration); },totalDuration); } Which produces a timing flaw where the message slowly begins to change during the transition period rather than when hidden; I then thought of removing all of this code (which handles closures, in the midst of it all) and replacing the message's animation functionality with 11 simple lines of CSS: .message{ animation: transit 4s; animation-iteration-count:infinite; } #keyframes transit { 0% {transform:translateX(-150%)} 25% {transform:translateX(50%)} 75% {transform:translateX(50%)} 100% {transform:translateX(150%)} } Afterwards changing the message at a set interval, in coordination with the time that the message is off screen. However, I don't know how I can do this. I'm thinking I need some sort of hybrid of setInterval and a loop; a loop that only loops after an interval of time has passed. How is this (or the next best thing) achieved?
I started thinking about the way a loop and setInterval() works, and I realized that what a loop is really doing is setting an interval of 0, checking a condition and then incrementing a variable. I can make my own for loop-setInterval hybrid by setting the interval, (in my case) skipping the condition, and incrementing my own variable. JS: var i = 0; var messages = ["message 1", "message2", "message 3"]; function writeAdd() { // Handling the closure return function () { $(".message").text(messages[i]); //if (condition === true){ // condition excluded i++; if(i === messages.length) i = 0; //creating the loop's repetition //} }; } function loopMessage(duration) { $(".message").css("-webkit-animation-play-state","running"); setInterval(writeAdd(), duration); //setting the interval } loopMessage(4000); CSS: .message-flow{ -webkit-animation: transit 8s; -webkit-animation-iteration-count:infinite; -webkit-animation-play-state:paused; } #-webkit-keyframes transit { 0% { -webkit-transform:translateX(-2000px); } 25% { -webkit-transform:translateX(0px); } 75% { -webkit-transform:translateX(0px); } 100% { -webkit-transform:translateX(2000px); } } The JSFiddle
Animated PNG background with Javascript, but without loop?
I need help with an animated PNG in Javascript. I found how to animate a PNG background with Javascript here on Stack Overflow. But my problem is that I only need the animation onmouseover and onmouseout. And the animation should play only once, not in a loop, so when the user moves the mouse over a div the the animation in the background should play once and stop at the last frame, but when the user goes off the div, a reverse animation should play once and stop at the last (first) frame. The script I found here is: The style: #anim { width: 240px; height: 60px; background-image: url(animleft.png); background-repeat: no-repeat; } The HTML: <div id="anim"></div> Javascript: var scrollUp = (function () { var timerId; // stored timer in case you want to use clearInterval later return function (height, times, element) { var i = 0; // a simple counter timerId = setInterval(function () { if (i > times) // if the last frame is reached, set counter to zero i = 0; element.style.backgroundPosition = "0px -" + i * height + 'px'; //scroll up i++; }, 100); // every 100 milliseconds }; })(); // start animation: scrollUp(14, 42, document.getElementById('anim')) I hope anyone can help me, Thank you
To stop the animation after the first set of frames you do want to change the if condition to not reset the counter to zero but instead to clear the interval and stop it from reoccuring. To only let it play when you enter an element you can attach the animation function as an event listener and play the whole thing in reverse with another function that you plug into your onmouseout event.
Depending on your target browser and since your question is fairly vague I can recommend two alternatives to you: Use jQuery animate (all browsers, include ref to jquery) //Animate to x,y where x and y are final positions $('#anim').mouseenter(function(e) { $(this).animate({background-position: x + 'px ' + y + 'px'}, 4200); }) //Do same for mouseleave Use a css3 animation (using -webkit browser here) <style> #-webkit-keyframes resize { 100% { height: 123px; } } #anim:hover { -webkit-animation-name: resize; -webkit-animation-duration: 4s; } I would choose option 2 if you are doing mobile development or can choose only css3 capable browsers.