Flick IMG src attribute to simulate blinking - javascript

Newbie here! I'm sorry if this is very simple.
I have two images of a person, eyes open and eyes shut. The eyes closed file has a 'b' at the end, so:
'/images/person.png' (eyes open)
'/images/personb.png' (eyes closed)
What I'd like is to switch the src on 'mouseenter' very quickly, so that the image looks like it's blinking twice in quick succession.
I would really appreciate any help.
Thanks fellas!

Here's how to do it in HTML5:
Live example on JSFiddle
Just replace the background-color by background-image:url('your_url'); in your CSS.
HTML
<div id="your_flipping_img"></div>
JS
$('#your_flipping_img').bind('mouseover', function(){
$('#your_flipping_img').addClass('animate');
})
$('#your_flipping_img').bind('mouseout', function(){
$('#your_flipping_img').removeClass('animate');
})
CSS
#your_flipping_img{
background-color:#efefef;
width:150px;
height:150px;
}
.animate{
-webkit-animation: flicking .5s; /* Chrome, Safari, Opera */
animation: flicking .5s;
}
#-webkit-keyframes flicking {
0% {background-color: red;}
25% {background-color: #efefef;}
50% {background-color: red;}
100% {background-color: #efefef;}
}
/* Standard syntax */
#keyframes flicking {
0% {background-color: red;}
25% {background-color: #efefef;}
50% {background-color: red;}
100% {background-color: #efefef;}
}

You're going to probably have to do that with javascript.
Assuming your image is something like #blinkingimage:
function blinkImage(image,num) {
setTimeout(function() {
image.src = 'images/personb.png';
setTimeout(function() {
image.src = 'images/person.png';
}, 50); // Set this to however long you want the blink to be, in milliseconds
}, 50); // Set this to however long you want the delay to be, in milliseconds
}
$('#blinkingimage').hover(function() {
blinkImage($(this),1); //You said you want it to blink twice, so you'll need to call blinkImage twice
setTimeout(function() {
blinkImage($(this),2);
}, 100); // Set this to twice the length of one blink call
});

Related

How to reanimate in javascript on click?

I have created animation using keyframes in css, how can re use that animation onclick?
I have to change background of the header on click, like carousel, and header must be animated on every click. But it is not working. I set header.style.animation to null and rewrite header.style.animation = 'animate-bg 1s linear' in each click, still not working
Let's add your animation to a class, you can trigger the animation just by removing and adding the class again.
This solution uses setTimout to be sure that the browser renders the deletion.
document.getElementById("header").addEventListener("click", function(e){
e.target.classList.remove("anim");
setTimeout(function(){
e.target.classList.add("anim");
});
})
#keyframes animate-bg {
0% {background-color: red;}
25% {background-color: yellow;}
50% {background-color: blue;}
100% {background-color: green;}
}
.anim {
animation: animate-bg 2s linear;
}
<div id="header">Hello Header</div>
Please add your code in your question first.
Add a class "active" onclick button then
button.active header{
animation: animate-bg 1s linear;
}

Simple fadein not running smooth

I am a beginner in jQuery and JS and I wanted to make a simple fade in animation using the following code. Unfortunately the code is not running smooth, and despite reading up all the basics (at least I suppose so) I cannot get it to run smoothly. Can anyone point me in the correct direction on how to make a smooth fade in animation?
All my elements are visible in the beginning. I don't want to start with hidden elements as this could result in problems in my UI if there is no JS enabled.
Thank you.
$(function () {
$("#center_block").animate(
{
opacity: 0,
}, 0, function () {
$("#center_block").animate({
opacity: 1,
}, 250);
});
});
If you have a slow processor on your computer or if you are viewing javascript animations a mobile device the processor might not be able to cope with the animation. If you use CSS3 animations then the inbuilt browsers hardware acceleration is used, which is a lot more efficient.
All I am doing is using CSS3 animation to apply the fade.
#keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity:1;
}
}
#center_block {
animation: 1s ease-out fadeIn;
}
<div id="center_block">Look at me, I'm Mr Center Block</div>
There really is no need for JavaScript at all here. CSS animations can do this more easily with better performance (because they will leverage GPU hardware acceleration):
span {
font-size:3em;
font-weight:bold;
font-family:Arial;
border:1px solid grey;
background-color:aliceblue;
display:inline-block;
padding:10px;
opacity:0;
/* Configure the element to use the animation */
animation: 3s infinite fade;
}
#keyframes fade {
0% { opacity:0; }
50% { opacity:1; }
100% { opacity:0; }
}
<span>Hello</span>
Or, if you don't want the animation to be automatic and have some sort of trigger, then just add a CSS class to the object at the right time:
document.querySelector("button").addEventListener("click", function(){
document.querySelector("span").classList.add("animate");
});
span {
font-size:3em;
font-weight:bold;
font-family:Arial;
border:1px solid grey;
background-color:aliceblue;
display:inline-block;
padding:10px;
opacity:0;
}
.animate {
/* Configure the element to use the animation */
animation: 3s infinite fade;
}
#keyframes fade {
0% { opacity:0; }
50% { opacity:1; }
100% { opacity:0; }
}
<button>Click to Start</button>
<span>Hello</span>
I would advise using CSS animations as much as possible for the smoothest performance. A great library to get you started is animate.css. To use it, include the css library in your project and use javascript to add predefined classes to your components. In your case:
$('#center_block').addClass('animated fadeIn');
would fade in the #center_block element nicely.
If you don't want to hide the elements incase JS is disabled, then you need to hide them first using JS. Also, you're currently using 250ms, which is incredibly fast, and unlikely to be perceived by users.
$(document).on('ready', function(){
$('#center_block').hide().fadeIn(250);
});
If your elements already have opacity: 0; for the CSS, then you can add a transition to handle the animation:
#center_block{
opacity: 0;
transition: all .25s linear;
}
Then change the CSS value of opacity whenever the triggering condition is met:
$('#center_block').css('opacity','1');

how to change background color of my website on an interval [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Today I visited this site and it looked awesome the feature of changing background color with respect to time i tried searching for changebackground() but could not find it can you please tell me how to do it.
on each interval call.
setInterval(intr,2000);
function intr()
{
document.body.style.backgroundColor="#colorInHex";
}
Note I've edited this post to call the interval function by reference. See the evils of eval by douglas crockford for fuller explanation.
CSS Animation:
CSS Animation is currently supported on all browsers except Opera Mini. It takes advantage of hardware acceleration and is preferred to JavaScript animations. In fact, jQuery animations try to use CSS3 animations and fall back to JS if the browser doesn't support it.
You can literally take this code and drop it in. See the FIDDLE here.
body {
animation: colorchange 50s; /* animation-name followed by duration in seconds*/
/* you could also use milliseconds (ms) or something like 2.5s */
-webkit-animation: colorchange 50s; /* Chrome and Safari */
}
#keyframes colorchange
{
0% {background: red;}
25% {background: yellow;}
50% {background: blue;}
75% {background: green;}
100% {background: red;}
}
#-webkit-keyframes colorchange /* Safari and Chrome - necessary duplicate */
{
0% {background: red;}
25% {background: yellow;}
50% {background: blue;}
75% {background: green;}
100% {background: red;}
}
The site you referenced uses 10 second transitions, so I took the number of colors (5) and multiplied that by 10 seconds to arrive at an animation duration of 50s.
Then you take the number of steps or colors (5) minus 1 (for the 0%), so now 4, and divide 100 by it, so 25. This gives you your step distance, so 5 steps from 0-100%: 0%, 25%, 50%, 75%, 100%.
Since the request is pretty simple, I just used the color names. They are not specific and are open to browser/OS interpretation. If you want more specific colors, you can use this color generator and replace the color names with one of these values.
Original Answer:
CSS Transitions:
This site uses CSS transitions. There is a declaration of:
* {
-webkit-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
Then you define some color classes like:
.green {
background-color: rgba(0,255,0,1);
}
.red {
background-color: rgba(255,0,0,1);
}
.blue {
background-color: rgba(0,0,255,1);
}
Then you set different classes on the body tag, and that will cause the transition like that, because of the transition CSS you defined initially
EDIT: I misspoke, slightly. here is the ACTUAL transition on the body tag:
transition: all 10s ease-in-out;
Of course, the CSS colors on the body are being set with JS on a timer, but it's a trivial operation and the CSS does the bulk of the work, and you can do it more elegantly by simply setting classes than by setting the bg color directly with script.
<head>
<script type="text/javascript" language="javascript">
/* Method To Generate Random Numbers Between "0-255" for RGB Color-code Format & Assign To Body-Backgrond-Style */
function bgDisco()
{
var x =Math.round(255*Math.random());
var num1 =getHex(x);
var y =Math.round(255*Math.random());
var num2 =getHex(y);
var z =Math.round(255*Math.random());
var num3 =getHex(z);
document.body.style.background="#"+num1+num2+num3;
setTimeout("bgDisco",1000);
}
/* Method To Convert Decimal To Hexadecimal */
function getHex(dec)
{
var hexArray = new Array( "0", "1", "2", "3","4", "5", "6", "7","8", "9", "A", "B","C", "D", "E", "F" );
var code1 = Math.floor(dec / 16);
var code2 = dec - code1 * 16;
var decToHex = hexArray[code2];
return (decToHex);
}
</script>
</head>
Now on the body part call the "bgDisco()" in onload event.
<body onload="bgDisco()">
This my be what you are looking for:
<style>
body {
background: #fff;
background-color: rgb(145, 207, 161);
font-family: 'Raleway', sans-serif;
transition: all 10s ease-in-out;
}
* {
-webkit-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
</style><script type="text/javascript">
function cb()
{
var c = "#1abc9c #2ecc71 #3498db #ea5b4d #9b59b6 #34495e #16a085 #27ae60 #2980b9 #8e44ad #2c3e50 #f1c40f #e67e22 #e74c3c #f39c12 #d35400 #c0392b #06b3db #4ed486 #6139f6 #e3b63d #dc3d66 #bd3559 #bd54cd #0082c8 #16528e #e54b4b #a2c5bf #167c80 #72616e #e8846b #ea5b4d #72BDC2".split(" ");
var d = Math.floor(Math.random() * c.length);
d = c[d];
document.body.style.background=d;
setTimeout("cb()",1000);}
</script>
<body onload="cb()">
If you look at the code of the page, you will see this:
<body onload="prettyPrint(); changebackground();" id="main">
I will dig up an I will post here the changebackground() function. I think that's you want.

Blinking a div with background-color in jquery using setInterval

the code :
<div id="divtoBlink" ></div>
css:
#divtoBlink{
width:100px;
height:20px;
background-color:#627BAE;
}
javascript:
setInterval(function(){
$("#divtoBlink").css("background-color","red");
},100)
but nothing is happening can anyone tell me what i am doing wrong ?
fiddle Here
I suggest you don't change the color with javascript. It's better practice to do this via CSS. Changing styles should be done in a stylesheet, not in JS (in case if you want other/more properties changed).
You toggle a class, that class has a background definition (in this example, if you want you can add more properties). A fiddle as DEMO
<div id="divtoBlink" ></div>
.blinker{
background: red;
}
let $div2blink = $("#divtoBlink"); // Save reference for better performance
let backgroundInterval = setInterval(function(){
$div2blink.toggleClass("blinker");
},100)
If you feel like a wild mood, you can add some css3 animation to it
#div2blink{
transition: backgroundColor 0.05s ease-in-out;
}
Made a demo for the animation: DEMO (I slowed it down in the example!)
DEMO
setInterval(function () {
$("#divtoBlink").css("background-color", function () {
this.switch = !this.switch
return this.switch ? "red" : ""
});
}, 100)
.blink-div {
background: green;
animation: flash 2s ease infinite;
}
<div class="blink-div">
Hello World
</div>
Another way to animate a div is by using the css3 animations.
.blink-div {
animation: flash 2s ease infinite;
}
Yet another example, but with much color and speed (based on martijn's example). Seizure warning:
var $div2blink = $("#divtoBlink"); // Save reference, only look this item up once, then save
var color = 0
var color_classes = ["backgroundRed", "backgroundYellow", "backgroundBlue"];
var backgroundInterval = setInterval(function(){
color++;
if (color === 3){
color = 0;
}
$div2blink.toggleClass(color_classes[color]);
},10)
http://jsfiddle.net/LkuNB/1983/
You can also do it with pure CSS:
#divtoBlink{
-webkit-animation: bgblink 3s; /* Chrome, Safari, Opera */
-webkit-animation-iteration-count: infinite; /* Chrome, Safari, Opera */
}
#-webkit-keyframes bgblink {
from {background-color: #fff;}
50% {color:#000}
to {background-color: #fff;}
}
#keyframes bgblink {
from {background-color: #fff;}
50% {background-color:#000}
to {background-color: #fff;}
}
Please have a look at below code
HTML:
<div id="divtoBlink" ></div>
CSS:
#divtoBlink{
width:100px;
height:20px;
background-color:#627BAE;
}
.class2{
background-color:#ff0000 !important;
}
JS :
setInterval(function(){
$("#divtoBlink").toggleClass("class2");
},100)
Try this to change the color one time to "red", change background-color to backgroundColor
setInterval(function(){
$("#divtoBlink").css("backgroundColor","red");
},100)
If you want to toggle the class, than you have to do it with .toggle

jQuery Animate() and BackgroundColor

I'm trying to create a simple pulse effect by changing the background color using JQuery. However, I can't get the backgroundColor to animate.
function show_user(dnid) {
/* dnid is HTML ID of a div. */
if (! $(dnid).is(':visible')) {
$(dnid).show()
}
$('html, body').animate({scrollTop: $(dnid).offset().top});
$(dnid).animate({backgroundColor: "#db1a35"}, 1200);
}
What's strange is that this alternate animation works:
$(dnid).animate({opacity: "toggle"}, 1200);
But it's not what I want at all.
Additionally the show() and scroll functionality in the function work fine. It's just the background color animation that doesn't.
The function above is called by this link
Locate Me
Could someone help me animate the background color?
=========
Thanks everyone for the help. Lots of similar answers. Here's what I ended up with
In my header
<script src="http://code.jquery.com/color/jquery.color-2.1.2.min.js"></script>
Then in my show_user function right after the scroll animation.
var bgcol = $(dnid).css('backgroundColor');
$(dnid).animate({backgroundColor: "#db1a35"}, 2000);
$(dnid).animate({backgroundColor: bgcol}, 2000);
That gives a relatively quick red "pulse" that will draw the user's eyes.
Again, thanks for the help.
jQuery cannot animate colours by default. In order to animate colours, use the official jQuery.Color plugin.
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).
Source
jQuery supports animation between any numeric CSS properties, which does not include colors. However, there are other libraries that make animating colors possible. One such library is the aptly-named jQuery Color. Its readme page shows several examples of how to use it to animate between colors using the jQuery .animate() function
Use the CSS animation property and keyframes
See it in action
HTML
<div></div>
CSS
div {
background-color: red;
height: 200px; width: 200px;
-webkit-animation: pulse 1s ease-in 0 infinite normal both;
-moz-animation: pulse 1s ease-in 0 infinite normal both;
-o-animation: pulse 1s ease-in 0 infinite normal both;
animation: pulse 1s ease-in 0 infinite normal both;
}
#-webkit-keyframes pulse {
0% { background-color: red; }
65% { background-color: #7F0093; }
100% { background-color: blue; }
}
#-moz-keyframes pulse {
0% { background-color: red; }
65% { background-color: #7F0093; }
100% { background-color: blue; }
}
#-ms-keyframes pulse {
0% { background-color: red; }
65% { background-color: #7F0093; }
100% { background-color: blue; }
}
#-o-keyframes pulse {
0% { background-color: red; }
65% { background-color: #7F0093; }
100% { background-color: blue; }
}
#keyframes pulse {
0% { background-color: red; }
65% { background-color: #7F0093; }
100% { background-color: blue; }
}
you must first set the background to the from color or it wont do anything 2nd time around.
You also typoed the css property 'background-color' and put it in quotes like i didn't :)
$(dnid).css({'background-color': "#ffffff"});
$(dnid).animate({'background-color': "#db1a35"}, 1200);
Just add this below your jQuery script and you are done:
<script src="https://cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>

Categories