How can I create an efficient infinitely looping waving text animation? - javascript

This is the effect I am trying to create (JSFiddle):
$('.header h1 span').each(function() { // each letter is contained inside a <span> element
var that = $(this);
setTimeout(function() {
that.animate({
top: "-10px"
}, animateTime / 2)
.animate({
top: "10px"
}, animateTime / 2);
}, that.index() * 100);
});
Result:
It appears to be successful. However, I ran into the problem of it looking like this after switching tabs, then coming back:
In the fiddle above, I've tried to "fix" this by making the animation stop when the tab is unfocused. It's better than when I WASN'T checking for tab unfocusing, but it still has problems. This is the code I'm using to do that:
var running = true;
document.addEventListener('visibilitychange', function(){
console.log("Running:" + running);
running = !document.hidden;
if(!running) clearQueues();
})
If the user spends less than a couple seconds unfocused from the tab, the animation looks like the second GIF again, and I don't see a way to avoid that. I've tried using requestAnimationFrame() but I can't figure out how to make it behave correctly.
So, my question is: how do I prevent the animation from being affected by the tab being unfocused?
Bonus points (figuratively) if you can help me make it more efficient on mobile, too.

I'm not sure if this solves the stuttering for you or not. This strategy is similar in concept to what you are doing, but uses CSS animation rather than js.
(function(){
var el = document.querySelectorAll(".wavey")[0];
var oldText = el.innerText
var newHtml = "";
for (var i in el.innerText) { newHtml += ("<span style='animation-delay: " + i/10 + "s;'>" + oldText[i] + "</span>"); }
el.innerHTML = newHtml;
})();
#keyframes wave {
from { transform: translateY(0); }
to { transform: translateY(-1em); }
}
h1.wavey { margin-top: 2em; }
h1.wavey span {
display: inline-block;
animation-duration: 1s;
animation-name: wave;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-timing-function: ease-in-out;
}
<h1 class="wavey">Hello World</h1>

Related

How to set a css animation class variable with Javascript/jQuery?

I've been implementing some CSS animations as named classes so I can easily add/remove any associated animation for an element, making it "available" for subsequent or repeat animations.
I'm dipping my toes into using CSS variables and it's currently throwing me for a loop. I'm trying to allow the user to rotate an active image in 90 degree increments. In the code example below, I'm showing only the positive 90 button click event.
*.scss
:root {
--rotation-degrees: 90;
}
#keyframes rotate {
100% {
transform: rotate(var(--rotation-degrees)+'deg');
}
}
.animation-rotate {
--rotation-degrees: 90;
// NOTE: I suspect the variable does not need to be supplied here, removing does
// not fix the issue, at least in isolation
animation: rotate(var(--rotation-degrees)) 0.2s forwards;
}
*.js
let degrees = 0;
function rotate(degrees_increment) {
degrees += degrees_increment;
// The use of document.documentElement.style.setProperty is something I've seen
// used in many of the articles I've read as a means to "get to" the css variable,
// so I'm simply blindly copying it's use here
document.documentElement.style.setProperty('--rotation-degrees', degrees +'deg');
$('#main-image-slider img').addClass('animation-rotate');
}
$('#rotate-right-button').on('click', function(event) {
event.preventDefault();
rotate(90);
});
Thank you in advance for any insights and help you can give!
I don't think it's possible to concatenate a CSS variable with a string as you were trying in your CSS:
transform: rotate(var(--rotation-degrees)+'deg');
It's better to handle that with JavaScript.
I think the main issue you're having is that the class needs to be removed after the animation has run (in order for it to be able to run again). You can do that with the animationend event listener.
Demo below:
const DIV = $('div');
const BUTTON = $('#rotate-right-button');
const SPAN = $('#variable-value');
const PROPERTY_NAME = '--rotation-degrees';
const DEG = 'deg';
const ROOT = document.documentElement;
const ElementClass = {
ROTATE_ANIMATION: 'animation-rotate'
}
const ROTATION_VALUE = 90;
const Event = {
CLICK: 'click',
ANIMATION_END: 'animationend'
}
let degrees = 0;
function rotate(degrees_increment) {
degrees += degrees_increment;
ROOT.style.setProperty(PROPERTY_NAME, degrees + DEG);
SPAN.html(`${PROPERTY_NAME}: ${degrees + DEG}`);
}
BUTTON.on(Event.CLICK, function() {
DIV.addClass(ElementClass.ROTATE_ANIMATION);
DIV.on(Event.ANIMATION_END, function(event) {
$(this).removeClass(ElementClass.ROTATE_ANIMATION);
});
rotate(ROTATION_VALUE);
});
#keyframes rotate {
100% {
transform: rotate(var(--rotation-degrees));
}
}
.animation-rotate {
animation: rotate 0.2s;
}
div {
background: red;
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<button id="rotate-right-button">rotate</button>
<br>
<span id="variable-value"></span>
I think the highlighted code is not triggering the animation again when adding a class -
Existing Code
var angle = 0;
$("#rotate").click(function(e){
angle+= 90;
document.documentElement.style.setProperty('--deg', angle+'deg');
var el = $(".square");
var newone = el.clone(true);
el.before(newone);
$(".square:last").remove();
});
:root {
--deg: 180deg;
}
#keyframes rotate {
100% {transform: rotate(var(--deg));}
}
.animation-rotate {
animation: rotate 0.9s forwards;
}
.square {
background: hsl(300, 90%, 52%);
width: 15vmin;
height: 15vmin;
border-radius: 10%;
margin: 25px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="square animation-rotate"></div>
<div>
<button class="btn btn-sm btn-success" id="rotate">Rotate</button>
</div>
</div>
I'm not sure I understand your code, but here's my take on it.
When the user clicks, you can either:
- add/remove a CSS class. In that case the values for the rotation are already set in your CSS.
- rotate the element directly in JavaScript, for instance by dynamically setting a CSS rule.
Seems to me like you're doing both at the same time?

easing speed of blink for text in a jackpot game

I am making a jackpot game with a selector very similar to this one
I have absolutely no idea where to start. My first thought was to use an array of randomly selected numbers sent from the server side to avoid cheating and animate those with jquery or css.
Then i thought about useing just jquery since i know it better and having the blink interval be a recursive fucnction that returns the values for easing speed i want. (the values would be pretty much exactly like in the video, no more than 3-4 seconds).
$('.blink').blink(); // default is 500ms blink interval.
$('.blink').blink(100); // causes a 100ms blink interval.
But now I am at a loss for where to get started since this has to be mobile friendly. What would you do?
UPDATE
$( document ).ready(function() {
var time = 0;
var diff = 50;
var minTime = 0;
var maxTime = 7000;
function easeInOutExpo(t, b, c, d) {
t /= d;
return c*t*t*t + b;
};
$("#clickme").click(function() {
for (var i = 0, len = diff; i <= len; i++) {
(function(s) {
setTimeout(function() {
$('#book').html("Page " + s + " turned");
}, time);
})(i); //<--------------i have no clue what this does------------
time = easeInOutExpo(i, minTime, maxTime, diff);
}
});
});//document ready
I've gotten the basic mechanic down, but when you click on it a second time instead of 50 it goes to 0. this is not good behavior as I am going to use these numbers to iterate through a randomly generated array.
Can anyone explain this behaviour? I've included a JS fiddle here. Thank you!
You can use simple css animation.
#keyframes blink {
0% { background-color:red; }
10% { background-color:purple; }
20% { background-color:gray; }
30% { background-color:green; }
40% { background-color:white; }
50% { background-color:cyan; }
65% { background-color:yellow; }
100% { background-color:black }
}
.Blink{
animation: blink 2s 1 ease-out;
background-color:black;
height:100px;
width:100px;
}
<div class="Blink">

CSS fade out multiple times

I'm making a website which will let you update an SQL table, and I want to add some sort of feedback when a button is clicked. I have made an invisible button (opacity=0) which lies to the right of each row as a status. I made this JS fade() function to set the opacity to 1, then slowly bring it back to 0, so a message pops up then fades away.
function fade () {
var invis = document.getElementById("invis".concat(num.toString()));
if(invis.style.opacity > .990) {
invis.style.opacity = (invis.style.opacity) - .001;
setTimeout(fade, 50);
} else if(invis.style.opacity > 0) {
invis.style.opacity = (invis.style.opacity) - .05;
setTimeout(fade, 50);
}
}
The trouble is, since webpages are single-threaded, any other action will interrupt the animation and leave behind a half-faded status. So that's no good. So now I am trying to set up the invisible buttons to change class when a new row is updated. The new class looks like this:
.invisible_anim {
...
opacity: 0;
animation:trans 3000ms;
}
#keyframes trans {
0% {
opacity: 1;
}
50% {
opacity: 1;
}
This works fine, except it only works once. From here I cannot get the animation to play a second time. I have tried changing the class back to "invisible" then "invisible_anim" with no luck. I also can't use JQuery or Webkit. I'm wondering if there's some flag you can set for a button without actually clicking on it so I can reset the class when I need to? Or even some way to thread my JS function so I can stick with that.
If you would like to play the animation multiple times (see docs here: https://developer.mozilla.org/en-US/docs/Web/CSS/animation), if you would like to play it twice only.
so this:
.invisible_anim {
...
opacity: 0;
animation:trans 3000ms;
}
#keyframes trans {
0% {
opacity: 1;
}
50% {
opacity: 1;
}
would turn to
.invisible_anim {
...
opacity: 0;
animation:trans 3s 2 ;
}
#keyframes trans {
0% {
opacity: 1;
}
50% {
opacity: 1;
}
EDIT:
Apparently the requirements are different than what I thought. Instead the solution seems to be to key off the animation event located at https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations and then when that animation done do what you need to do: so in JS-only
var e = document.getElementById("watchme");
e.addEventListener("animationend", listener, false);
function listener(){
//do what you need to do here
}
Just be careful, the reason for this is that most browsers have different "animationend" events that fire at different times. So definitely will need to be tested in different browsers to make sure that the animation event is firing at the right time. There's a post at (https://css-tricks.com/controlling-css-animations-transitions-javascript/) that details some of the issues you might encounter.
Have you considered using the CSS property "transition"? JavaScript has an event listener called "transitionend" that can trigger when your transition has ended, which you can use to reset the button.
First set the area for your alert button with the id invis.
CSS:
#invis {
opacity: 1;
transition: opacity 3s;
}
Then in JavaScript, generate your button and its content, which will appear at opacity 1, then transition to opacity 0. Your addEventListener will trigger when the animation is done, remove the button and reset the opacity for the next trigger.
JavaScript:
var invis = getElementByID("invis");
function fade() {
var button = document.createElement("button");
invis.appendChild(button);
invis.style.opacity = ("0");
invis.addEventListener("transitionend", function(){
invis.removeChild(button);
invis.style.opacity = ("1");
});
}
You can add the fade() function to your EventListener for the user "click."
This is my first time answering on StackOverflow, I hope this helps!
You need to start transparent then show then hide:
#keyframes trans {
0% {
opacity: 0;
}
50% {
opacity: 1;
}
100% {
opacity: 0;
}
}
Then simply add your class (remove after the 3000ms time period)

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 })

Moving Background image in a loop from left to right

I would like to have a moving background image on my page from left to right exactly the same way as in following website http://kxip.in , please suggest how to achieve this.
Thanks & Regards
An interesting question with a challenging solution. Thankfully, stackoverflow.com is here to help you do your work!
Obviously, you'll need jQuery! So, grab some jQuery and then come back.
Back? Great.
Let's start off. First, add this bit of line to your code:
$(function(){
})
So, what is that $ magic stuff? Nevermind you actually learning that! We're here to get answers, not learn! But, if you're the curious type, open up a new tab and ask the following question on stackoverflow.com, "what is this $(function(){ }) stuff". Someone will fill you in! Don't forget to tag JQUERY!
Ok, we want to animate a background image. TOUGH. Of course, there are a lot of ways to do this (HTML, CSS, and JAVASCRIPT always have more than one way to do this!) but I prefer the JQuery way. Remember that weird dollar signy stuff at the top? Let's go back to that!
$(function(){
setInterval(function(){
}, 500);
})
We just added some more programs! setInterval is a counter that counts up to 500 milliseconds and then runs the code inside. Why 500? I don't know, I just like magic numbers. So we have a timerjiggymathing, we need some more programs in it. How do we add a background?
$(function(){
setInterval(function(){
$('body').css('background-position', '0 0');
}, 500);
})
Ok, now we're getting somewhere! Our jQueries are actually now setting the background position to 0, 0. Not so interesting yet. Let's see if we can do some more.
$(function(){
var x = 0;
setInterval(function(){
x-=1;
$('body').css('background-position', '0 ' + x + 'px');
}, 500);
})
Let's test it out!
http://jsfiddle.net/hY5Dx/
Oh man. That image is way too big and the stupid kitten is going UP! Back to the codes.
$(function(){
var x = 0;
setInterval(function(){
x-=1;
$('body').css('background-position', x + 'px 0');
}, 500);
})
http://jsfiddle.net/hY5Dx/1/
Ahhh, more like it! But, man...is it awfully slow. Let's upgrade that!
$(function(){
var x = 0;
setInterval(function(){
x-=1;
$('body').css('background-position', x + 'px 0');
}, 10);
})
http://jsfiddle.net/hY5Dx/2/
OH SNAPPPPPP. We got some scrolling kittenz now! JavaQuery is AWESOME!
To be honest though, that background image isn't doing justice. Time to update that!
http://jsfiddle.net/hY5Dx/3/
Oh yeah, now we're kicking!!!
SO, there you have it! 1 of many, MANY ways to do what you want to do.
GOOD LUCK. HAVE FUN.
Here is a css solution:
FIDDLE
body {
background: url(http://kxip.in/images/mohalistadium.jpg) repeat;
-webkit-animation: loader 16s steps(100) infinite;
-moz-animation: loader 16s steps(100) infinite;
-ms-animation: loader 16s steps(100) infinite;
-o-animation: loader 16s steps(100) infinite;
animation: loader 16s steps(100) infinite;
}
#-webkit-keyframes loader {
from {
background-position: 0;
}
to {
background-position: -1600px 0;
}
}
#-moz-keyframes loader {
from {
background-position: 0;
}
to {
background-position: -1600px 0;
}
}
#-ms-keyframes loader {
from {
background-position: 0;
}
to {
background-position: -1600px 0;
}
}
#-o-keyframes loader {
from {
background-position: 0;
}
to {
background-position: -1600px 0;
}
}
#keyframes loader {
from {
background-position: 0;
}
to {
background-position: -1600px 0;
}
}
Its easy! Just use some simple javascript!
Checkout the jsFiddle
Code:
<html>
<head>
<title>BackGround Slide</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
// speed in milliseconds
var scrollSpeed = 70;
// set the default position
var current = 0;
// set the direction
var direction = 'h';
function bgscroll() {
// 1 pixel row at a time
current -= 1;
// move the background with backgrond-position css properties
$('body').css("backgroundPosition", (direction == 'h') ? current + "px 0" : "0 " + current + "px");
}
//Calls the scrolling function repeatedly
setInterval("bgscroll()", scrollSpeed);
</script>
<style type="text/css">
body {
background-image: url('http://kxip.in/images/mohalistadium.jpg');
}
</style>
</head>
<body>
</body>
</html>
Use some js/jQuery:
function move(){
var element = $('#selector');
element .css('background-position-x', (parseInt(element.css('background-position-x') - 10));
//Check if need to reset background-position-x to origin.
}
you can use marquee tag in HTML5. you can see the examples in http://www.quackit.com/html/codes/html_marquee_code.cfm.
The easiest way to achieve this i believe is to use using a little bit of Javascript.
You can find the javascript they user to use as an example here:
http://kxip.in/js/background-moving.js
// speed in milliseconds
var scrollSpeed = 70;
// set the default position
var current = 0;
// set the direction
var direction = 'h';
function bgscroll() {
// 1 pixel row at a time
current -= 1;
// move the background with backgrond-position css properties
$('div.background-image').css("backgroundPosition", (direction == 'h') ? current+"px 0" : "0 " + current+"px");
}
//Calls the scrolling function repeatedly
setInterval("bgscroll()", scrollSpeed);
I urge you however not to simply copy and paste because this will likely not work for you.

Categories