Repeatedly change background colour of picture onMouseOver - javascript

I have a picture and wish its background to change and repeatedly take random colours sequencially from all over the spectrum till the user's mouse exits the picture. I guess the solution should use setInterval (see this) and the following shall help:
var red = Math.round(Math.random() * 255);
var green = Math.round(Math.random() * 255);
var blue = Math.round(Math.random() * 255);
var bg = "background-color: rgb(" + red + "," + green + "," + blue + ");";
x.style = bg;
Here is a fiddle trying to implement what I have in mind: The first smiley should change colour onMouseOver and return to normal onMouseOut.
Here is what I have in mind: I want to implement what FontAwesome.com do on their logo at their footer: it changes colours onmouseover and stops otherwise. But that's not a picture, it's a font(?). Instead, I have a logo that I made transparent, and I want to change the background dynamically so that it replicates the nice trick of Fontawesome. Any ideas?
* Updated *
I am posting a detailed solution to my question below based on the answers of the community. Looks like I followed Leo's way but Rakibul's solution worked well too.

I achieved what I want.
I wanted my logo to change colours "nicely" when a user's mouse hovers over it (like magic and similar to FontAwesome's logo at their footer).
.OAlogo {
background-color: transparent;
animation-play-state: paused;
}
.OAlogo:hover {
animation: colorReplace 10s infinite;
animation-timing-function: linear;
animation-direction: alternate;
}
#keyframes colorReplace {
0% {
background-color: rgb(44, 132, 231);
}
10% {
background-color: rgb(61, 192, 90);
}
20% {
background-color: rgb(255, 211, 59);
}
30% {
background-color: rgb(253, 136, 24);
}
40% {
background-color: rgb(243, 129, 174);
}
50% {
background-color: rgb(34, 138, 230);
}
60% {
background-color: rgb(62, 192, 89);
}
70% {
background-color: rgb(255, 211, 59);
}
80% {
background-color: rgb(71, 193, 86);
}
90% {
background-color: rgb(253, 126, 20);
}
100% {
background-color: rgb(233, 109, 132);
}
}
<img class="OAlogo" src="http://www.stouras.com/OperationsAcademia.github.io/images/OA-logo-solo.png" style="background: black;" width="100">

You have to declare setInterval() with your required time interval (In the example below 500 is set) for the color to be changed randomly on definite interval. And onmouseover is used to simply detect the hover on the image and then it sets the color randomly. Finally, when onmouseout is detected, the color changes to no-color.
var randomColor = function() {
var r = Math.floor(Math.random() * 12);
var g = Math.floor(Math.random() * 128);
var b = Math.floor(Math.random() * 100);
return "#" + r + g + b;
};
var colorChange;
document.getElementById("myImage").onmouseover = function() {
colorChange = setInterval(function() {
document.getElementById("myImage").style.backgroundColor = randomColor();
}, 500);
};
document.getElementById("myImage").onmouseout = function() {
this.style.backgroundColor = "";
clearInterval(colorChange);
};
<img id="myImage" src="https://www.w3schools.com/jsref/smiley.gif" alt="Smiley">

Use CSS animation to change colors and use the animation-play-state: pause on hover.
.button {
width:100px;
height:20px;
background-color: red;
animation: colorReplace 5s infinite;
}
.button:hover {
animation-play-state: paused;
}
#keyframes colorReplace
{
0% {background-color:red;}
30% {background-color:green;}
60% {background-color:blue;}
100% {background-color:red;}
}
<input type="submit" value="submit" class="button" />

You can just use the setInterval function to run your code over and over. You also had some minor errors in your code which I have fixed. See your updated fiddle here: https://jsfiddle.net/zvebco3r/3/
You can change the interval time (currently 25ms) to your desired length.
HTML:
<img id="img" src="https://www.w3schools.com/jsref/smiley.gif" alt="Smiley" width="32" height="32">
JS:
var img = document.getElementById('img');
img.onmouseover = function() {
changeIt = setInterval(function(){
var red = Math.floor(Math.random() * 255);
var green = Math.floor(Math.random() * 255);
var blue = Math.floor(Math.random() * 255);
img.style.backgroundColor="rgb("+red+","+green+","+blue+")";
},25);
}
img.onmouseout = function() {
this.style.backgroundColor="transparent";
clearInterval(changeIt);
}

Related

How to pause interval on mouseover and resume when the mouse is no longer over

I created a page where the background colors of a div change every so often. I want to make it so that when the mouse is over(or hovers) the color changer pauses where it is, as long as the mouse hovers there. And when the mouse no longer hovers the div, the colors continue to change where it left off. The closest examples I ran into on this website used JQuery solutions. I am not looking for a JQuery solution. I am looking for a javascript solution. I appreciate any and all of your responses. Thank You!
var dammit = document.getElementById("muck");
var colorChange = document.getElementById("color-changer");
var colors = ["red", "blue", "green", "pink"];
var counter = 0;
function changer() {
if (counter >= colors.length) {
counter = 0;
};
colorChange.style.background = colors[counter];
counter++;
};
var myTimer = setInterval(changer, 3000);
body {
background: #FDCA40;
margin: 0;
padding: 0;
-webkit-transition: background 0.9s;
-moz-transition: background 0.9s;
transition: background 0.9s;
}
div#muck {
width: 100%;
height: 100vh;
}
<body id="color-changer">
<div id="muck"></div>
</body>
There is no way to pause a timer, but you can just stop the currently running one and then start a new one.
(FYI: All browsers that are within 5 years old at least support CSS transitions. No need to vendor prefix that.)
var source = document.getElementById("muck");
var colorChange = document.getElementById("color-changer");
var colors = ["red", "blue", "green", "pink"];
var counter = 0;
function changer(){
if (counter >= colors.length){
counter = 0;
};
colorChange.style.background = colors[counter];
counter++;
};
var myTimer = setInterval(changer, 1000);
// Stop the current timer when mouseover
source.addEventListener("mouseover", function(){ clearInterval(myTimer)});
// Start a new timer when mouse out
source.addEventListener("mouseout", function(){ myTimer = setInterval(changer, 1000);});
body{
background: #FDCA40;
margin: 0;
padding: 0;
transition: background 0.9s;
}
div#muck{
width: 100%;
height: 100vh;
}
<body id="color-changer">
<div id="muck"></div>
</body>
You can do this purely in CSS but you need to use animation. I also added some CSS variables so the animation is easier to change.
body {
background: #FDCA40;
margin: 0;
padding: 0;
}
/* Safari 4.0 - 8.0 */
#-webkit-keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
#keyframes example {
0% {background-color: red;}
20% {background-color: blue;}
40% {background-color: green;}
80% {background-color: pink;}
100% {background-color: red;}
}
div#muck {
--animation-transition-speed: 0.9s;
--number-of-colors: 4;
width: 100%;
height: 100vh;
-webkit-animation-name: example;
-webkit-animation-duration: calc(var(--animation-transition-speed) * var(--number-of-colors));
animation-name: example;
animation-duration: calc(var(--animation-transition-speed) * var(--number-of-colors));
animation-iteration-count: infinite;
}
div#muck:hover {
animation-play-state: paused;
}
<body id="color-changer">
<div id="muck"></div>
</body>
While this doesnt really pouse the interval it mimics what you need very closely..
You can use a flag.. something like this:
var output = document.getElementById('id')
var isPaused = false;
var counter = 0;
window.setInterval(function() {
if(!isPaused) {
counter++;
if (counter >= colors.length) {
counter = 0;
};
colorChange.style.background = colors[counter];
}
}, 1000);
document.getElementById('muck').addEventListener('mouseenter', function(e) {
isPaused = true;
});
document.getElementById('muck').addEvenetListener('mouseleave', function(e) {
isPaused = false;
});
from Javascript - Pausing setInterval()

How do I create a vertical jQuery or CSS slider for an inline element

So basically I saw this really cool CSS animation on code pen (https://codepen.io/yoannhel/pen/sJpDj) and I've been trying to replicate it so that it would work for me. I was able to replicate the animation on the brackets with CSS fairly easily, but I have absolutely no idea how to do the transition between changing text like they did. I want to replicate the way that new text slides down into the visible inline view frame and then slides out.
I would prefer if this had a CSS only solution but at this point I'll take anything.
This is the code I have so far
var users = ["bob", "john", "world", "everyone"];
counter = 0;
setInterval(function() {
//slide down off screen
//Change Value
if (counter >= (users.length - 1)) {
elUser.textContent = users[counter];
counter = 0;
} else {
elUser.textContent = users[counter];
counter += 1
}
//reset to top
$("#user").animate({
bottom: '-=120'
});
//slide down on screen
}, 2000);
#keyframes WelcomeBrackets {
0% {
color: rgba(242, 12, 54, 0);
}
50% {
color: rgba(242, 12, 54, 1);
}
100% {
color: rgba(242, 12, 54, 0);
}
}
#user {
display: inline;
overflow: hidden;
}
.bracket {
animation: WelcomeBrackets 2s;
animation-iteration-count: infinite;
color: #2603c1;
}
<h1><span class="bracket">[ </span> Welcome <span id="user">User</span>
<span class="bracket"> ]</span>
</h1>
You did not call the correct id. change your Div ID as elUser and it will work.
var users = ["bob", "john", "world", "everyone"];
counter = 0;
setInterval(function() {
//slide down off screen
//Change Value
if (counter >= (users.length - 1)) {
elUser.textContent = users[counter];
counter = 0;
} else {
elUser.textContent = users[counter];
counter += 1
}
//reset to top
$("#user").animate({
bottom: '-=120'
});
//slide down on screen
}, 2000);
#keyframes WelcomeBrackets {
0% {
color: rgba(242, 12, 54, 0);
}
50% {
color: rgba(242, 12, 54, 1);
}
100% {
color: rgba(242, 12, 54, 0);
}
}
#user {
display: inline;
overflow: hidden;
}
.bracket {
animation: WelcomeBrackets 2s;
animation-iteration-count: infinite;
color: #2603c1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1><span class="bracket">[ </span> Welcome <span id="elUser">User</span>
<span class="bracket"> ]</span>
</h1>
You can get the output using Slide Up and Slide Down animation.
To get the knowledge on that please refer the snippet below
#keyframes WelcomeBrackets {
0% {
color: rgba(242, 12, 54, 0);
}
50% {
color: rgba(242, 12, 54, 1);
}
100% {
color: rgba(242, 12, 54, 0);
}
}
#user {
display: inline;
overflow: hidden;
}
.bracket {
animation: WelcomeBrackets 2s;
animation-iteration-count: infinite;
color: #2603c1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1><span class="bracket">[ </span> Welcome <span id="elUser">User</span>
<span class="bracket"> ]</span>
</h1>
<script>
var users = ["bob", "john", "world", "everyone"];
counter = 0;
setInterval(function () {
$('#elUser').slideDown(1000);
if (counter >= (users.length - 1)) {
elUser.textContent = users[counter];
$('#elUserelUser').slideDown(1000);
counter = 0;
} else {
elUser.textContent = users[counter];
$('#elUser').slideUp(1000);
counter += 1;
}
}, 2000);
</script>

Javascript settimeouts on html whack a mole game

I've been trying to create a html whack a mole game in which a mole has a class added to it at a certain interval, another timeout function is then triggered giving the user 3 seconds to click the mole and remove the class before a check is carried out which determines if that mole still has the class attached to it.
here is a jsfiddle of my game : https://jsfiddle.net/gko9puqf/1/ and below is my javascript.
var score = 0;
var numberofpipes = 9;
var lastnum = 0;
var intervalseconds;
var interval;
var haslost = false;
var checkpipetimer;
var timeoutfunc;
var timeoutinit;
var timers = [];
var burstingpipes = {};
var timeoutinit = setTimeout(startaburst, 3000);
$('#scorecontainer').text(score);
//starts a bursting pipe
function startaburst() {
clearTimeout(timeoutinit);
if (score < 10) {
intervalseconds = 2;
} else if (score >= 10 && score < 25) {
intervalseconds = 1.5;
} else if (score >= 25 && score < 40) {
intervalseconds = 1;
} else if (score >= 40 && score < 60) {
intervalseconds = 0.5;
} else if (score >= 60) {
intervalseconds = 0.25;
} else if (score > 100) {
intervalseconds = 0.1;
}
interval = intervalseconds * 1000;
burstingpipe();
//creating a loop with the new timeout value as the game gets harder.
//also assigning it to the timeoutfunc variable so i can cancel the loop later.
timeoutfunc = setTimeout(startaburst, interval);
}
//adds the bursting pipe attributes to the pipe intersections
function burstingpipe() {
randomnum = Math.floor(Math.random() * 9) + 1;
//cant be the same twice in case of overlapping
if ((randomnum == lastnum) || $("." + randomnum).hasClass("burstingpipe")) {
//if the random num is still valid after -1, -1
if (((randomnum - 1) >= 0) && !($("." + (randomnum - 1)).hasClass("burstingpipe"))) {
randomnum = (randomnum - 1);
//add one to the random number
} else if (((randomnum + 1) <= (numberofpipes)) && !($("." + (randomnum + 1)).hasClass("burstingpipe"))) {
randomnum = (randomnum + 1);
} else {
burstingpipe();
}
}
//make the lastnum the current number so we dont get 2 in a row
lastnum = randomnum;
randomdiv = $("." + randomnum);
console.log(randomdiv.hasClass("burstingpipe"));
//adds shake animation and red glow
console.log(randomnum);
randomdiv.addClass("burstingpipe");
//setting a timeout of 3 seconds, so th user has 3 seconds to press each
//bursting pipe before it bursts.
checkpipetimer = setTimeout(haspipeburst.bind(this, randomdiv), 3000);
}
//function to check if the pipe has burst.
function haspipeburst(pipecheck) {
console.log(pipecheck);
console.log(pipecheck.hasClass("burstingpipe"));
//checking to see if the pipe still has the class attached after 3 seconds
//and if the user has already lost.
if (pipecheck.hasClass("burstingpipe")) {
//if the pipe still has the class attached - game over.
haslost = true;
$("#result").text("you have lost");
//stopping the loop.
clearTimeout(timeoutfunc);
//changing the background color to make it look like the pipe has broken.
//(will possibly change to image in future)
//$(".hitpoint").removeClass("burstingpipe");
$(pipecheck).css("background-color", "#49c1e2");
}
}
//when the user clicks a hitpoint the class is removed and they gain a point.
$(document).on('click', '.hitpoint', function() {
if ($(this).hasClass("burstingpipe") && haslost == false) {
$(this).removeClass("burstingpipe");
score++;
$("#scorecontainer").text(score);
}
});
it works as expected up until the timeout gets significantly shorter (around a score of 40) and the moles glitch out as if the timeout was ignored.
I've been staring at the code for hours now and have made little progress so I am hoping you can help me out! i believe its something to do with the timeouts not being completed properly.
any help is greatly appreciated, thanks.
A bit of a late addition, but was working a bit on this in-between other tasks. As stated a problem with starting multiple timers is that you need to remember the specific timers and not only the last one. In the code below that is done by keeping a 'bursting pipe' inside a single class (function) with its own timer.
Perhaps I went a bit overboard, but as also stated by others, I liked the game you made :) One of the changes is not looping through all pipes to get a pipes that's not bursting, but remove the pipe from available pipes once it's bursting. This also negates the need for numbering the divs. More details in the code-comments. Of course you're free to ignore this code completely, but since I had it about finished, am posting it anyway.
Fiddle
var score = 24; //set higher for testing purposes
var pipes = $('.hitpoint').toArray() ,
last = null,
haslost = false,
interval = 2, //start interval
thresholds = {10: 1.5, 25: 1 , 40: 0.5, 60:0.25, 100 :1}; //interval thresholds
setTimeout(startaburst, 3000); //intial timeout (doesn't need to be cleared, because it's fired once)
$('#scorecontainer').text(score);
//starts a bursting pipe
function startaburst() {
if(haslost)return; //already lost
if(pipes.length>0){ //pick a pipe to burst unless all pipes allready bursting
var i;
while(true){
var p = pipes[i = Math.floor(Math.random() * pipes.length)]; //get random element from the available pipes
if(p!==last || pipes.length === 1)break;
}
pipes.splice(i,1); //remove pipe from available pipes
last = p; //remember last to prevent reusing the same pipe twice
new burstingPipe(p);
}
setTimeout(startaburst, interval * 1000); //wait until staring the new burst. interval is increased inside backInGame if the score increases
}
function burstingPipe(pipe){
this.pipe = $(pipe);
this.pipe.addClass("burstingpipe");
function checkBurst(){
this.dispose();
if(haslost)return; //already lost on other pipe
haslost = true;
$("#result").text("you have lost");
//changing the background color to make it look like the pipe has broken.
//(will possibly change to image in future)
this.pipe.css("background-color", "#49c1e2");
};
this.dispose=function(){
this.pipe.off('click'); //unbind click (no longer bursting or already burst)
this.pipe.removeClass("burstingpipe");
}
function backInGame(){
clearTimeout(this.timer); //clear the burst timeout (specific for this pipe)
this.dispose();
pipes.push(this.pipe[0]); //make pipe available again (NB, because the array contains of DOM elements and not jquery objects, [0] is needed)
var int = thresholds[++score]; //increase the score and check if interval should be increased for the new score
if(int && int < interval){
//optional: some message or css that interval is increased
interval =int;
}
$("#scorecontainer").text(score);
}
this.pipe.click(backInGame.bind(this)); //bind the click
this.timer =setTimeout(checkBurst.bind(this), 3000);
}
#keyframes shake {
5%,
15%,
25%,
35%,
45%,
55%,
65%,
75%,
85%,
95% {
left: 0;
right: 1vh;
outline: none;
border-color: red;
box-shadow: 0 0 10px red;
}
10%,
20%,
30%,
40%,
50%,
60%,
70%,
80%,
90%,
100% {
left: 1vh;
right: 0;
outline: none;
border-color: red;
box-shadow: 0 0 10px red;
}
}
#-webkit-keyframes shake {
5%,
15%,
25%,
35%,
45%,
55%,
65%,
75%,
85%,
95% {
left: 0;
right: 1vh;
outline: none;
border-color: red;
box-shadow: 0 0 10px red;
}
10%,
20%,
30%,
40%,
50%,
60%,
70%,
80%,
90%,
100% {
left: 1vh;
right: 0;
outline: none;
border-color: red;
box-shadow: 0 0 10px red;
}
}
#-moz-keyframes shake {
5%,
15%,
25%,
35%,
45%,
55%,
65%,
75%,
85%,
95% {
left: 0;
right: 1vh;
outline: none;
border-color: red;
box-shadow: 0 0 10px red;
}
10%,
20%,
30%,
40%,
50%,
60%,
70%,
80%,
90%,
100% {
left: 1vh;
right: 0;
outline: none;
border-color: red;
box-shadow: 0 0 10px red;
}
}
#-o-keyframes shake {
5%,
15%,
25%,
35%,
45%,
55%,
65%,
75%,
85%,
95% {
left: 0;
right: 1vh;
outline: none;
border-color: red;
box-shadow: 0 0 10px red;
}
10%,
20%,
30%,
40%,
50%,
60%,
70%,
80%,
90%,
100% {
left: 1vh;
right: 0;
outline: none;
border-color: red;
box-shadow: 0 0 10px red;
}
}
html {
height: 100%;
width: 100%;
}
* {
margin: 0;
padding: 0;
}
body {
height: 100%;
width: 100%;
}
#gamecontainer {
height: 100%;
width: 100%;
background-color: #49c1e2;
}
#gameinformation {
height: 10%;
display: flex;
flex-direction: row;
align-items: center;
padding-left: 10%;
}
#pipecontainer {
height: 80%;
width: 100%;
display: flex;
flex-direction: column;
justify-content: space-around;
}
.pipe {
height: 8vh;
width: 100vw;
background-color: #a5a5a5;
display: flex;
flex-direction: row;
justify-content: space-around;
}
.hitpoint {
height: 10vh;
width: 10vh;
background-color: #6d6d6d;
border-radius: 2vh;
position: relative;
bottom: 1vh;
cursor: pointer;
}
#scoretext {
color: #fff;
font-size: 6vh;
}
#scorecontainer {
color: #fff;
font-size: 6vh;
}
#statusupdate {
color: #fff;
font-size: 6vh;
}
.burstingpipe {
animation-name: shake;
animation-duration: 3s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="gamecontainer">
<div id="gameinformation">
<p id="scoretext">Score: </p>
<div id="scorecontainer">
</div>
</div>
<div id="pipecontainer">
<div class="pipe">
<div class="hitpoint"></div>
<div class="hitpoint"></div>
<div class="hitpoint"></div>
</div>
<div class="pipe">
<div class="hitpoint"></div>
<div class="hitpoint"></div>
<div class="hitpoint"></div>
</div>
<div class="pipe">
<div class="hitpoint"></div>
<div class="hitpoint"></div>
<div class="hitpoint"></div>
</div>
</div>
<div id="statusupdate">
<p id="result"></p>
</div>
</div>
I liked your game :)
And here is your problem: when the score increase, your are decreasing the timeout interval to have multiple shacked zone at the same time. And to stop all timer if the user loose, you are using this line:
timeoutfunc = setTimeout(startaburst, interval);
and then
clearTimeout(timeoutfunc);
This won't work because timeoutfunc will only contain the last launched Timeout and not all launched timeout (remember, while the check is done each 3 sec, the shaking timeout will run multiple times). So you need an array to keep all intervals and then clear all off them.
I updated your fiddle (also removed some unneeded lines)
var score = 0;
var numberofpipes = 9;
var lastnum = 0;
var intervalseconds;
var interval;
var haslost = false;
var checkpipetimer;
var timeoutfunc = [];
var timers = [];
var burstingpipes = {};
setTimeout(startaburst, 3000);
$('#scorecontainer').text(score);
//starts a bursting pipe
function startaburst() {
if (score < 10) {
intervalseconds = 2;
} else if (score >= 10 && score < 25) {
intervalseconds = 1.5;
} else if (score >= 25 && score < 40) {
intervalseconds = 1;
} else if (score >= 40 && score < 60) {
intervalseconds = 0.5;
} else if (score >= 60) {
intervalseconds = 0.25;
} else if (score > 100) {
intervalseconds = 0.1;
}
interval = intervalseconds * 1000;
burstingpipe();
//creating a loop with the new timeout value as the game gets harder.
//also assigning it to the timeoutfunc variable so i can cancel the loop later.
timeoutfunc.push(setTimeout(startaburst, interval));
}
//adds the bursting pipe attributes to the pipe intersections
function burstingpipe() {
randomnum = Math.floor(Math.random() * 9) + 1;
//cant be the same twice in case of overlapping
if ((randomnum == lastnum) || $("." + randomnum).hasClass("burstingpipe")) {
//if the random num is still valid after -1, -1
if (((randomnum - 1) >= 0) && !($("." + (randomnum - 1)).hasClass("burstingpipe"))) {
randomnum = (randomnum - 1);
//add one to the random number
} else if (((randomnum + 1) <= (numberofpipes)) && !($("." + (randomnum + 1)).hasClass("burstingpipe"))) {
randomnum = (randomnum + 1);
} else {
burstingpipe();
}
}
//make the lastnum the current number so we dont get 2 in a row
lastnum = randomnum;
randomdiv = $("." + randomnum);
console.log(randomdiv.hasClass("burstingpipe"));
//adds shake animation and red glow
console.log(randomnum);
randomdiv.addClass("burstingpipe");
//setting a timeout of 3 seconds, so th user has 3 seconds to press each
//bursting pipe before it bursts.
checkpipetimer = setTimeout(haspipeburst.bind(this, randomdiv), 3000);
}
//function to check if the pipe has burst.
function haspipeburst(pipecheck) {
console.log(pipecheck);
console.log(pipecheck.hasClass("burstingpipe"));
//checking to see if the pipe still has the class attached after 3 seconds
//and if the user has already lost.
if (pipecheck.hasClass("burstingpipe")) {
//if the pipe still has the class attached - game over.
haslost = true;
$("#result").text("you have lost");
//stopping the loop.
for (var i = timeoutfunc.length - 1; i >= 0; i--) {
clearTimeout(timeoutfunc[i]);
}
//changing the background color to make it look like the pipe has broken.
//(will possibly change to image in future)
//$(".hitpoint").removeClass("burstingpipe");
$(pipecheck).css("background-color", "#49c1e2");
}
}
//when the user clicks a hitpoint the class is removed and they gain a point.
$(document).on('click', '.hitpoint', function() {
if ($(this).hasClass("burstingpipe") && haslost == false) {
$(this).removeClass("burstingpipe");
score++;
$("#scorecontainer").text(score);
}
});

javascript css3 change background color every 2 seconds

How can I change the HTML background color automatically every 2 seconds? HTML5 with CSS3 fade in or fadeout?
I tried to use transition with timer and CSS target without any success
input[type=checkbox] {
position: absolute;
top: -9999px;
left: -9999px;
}
label {
display: block;
background: #08C;
padding: 5px;
border: 1px solid rgba(0,0,0,.1);
border-radius: 2px;
color: white;
font-weight: bold;
}
input[type=checkbox]:checked ~ .to-be-changed {
color: red;
}
A few changes A variation on this should work in modern browsers, if you know the colors and the number of colors in advance:
.animate-me {
-webkit-animation: bgcolorchange 4s infinite; /* Chrome, Safari, Opera */
animation: 4s infinite bgcolorchange;
}
#keyframes bgcolorchange {
0% {
background-color: red;
}
25% {
background-color: green;
}
50% {
background-color: yellow;
}
75% {
background-color: yellow;
}
100% {
background-color: red;
}
}
/* Chrome, Safari, Opera */
#-webkit-keyframes bgcolorchange {
0% {background: red;}
25% {background: yellow;}
75% {background: green;}
100% {background: blue;}
}
<div class="animate-me">Trippy! Give me a headache!</div>
http://jsfiddle.net/nnw7xza2/1/
Click to demohere!
Figure it up with:
-css3
-html5
-javascript timer
var arrColor = ["#45c1bf", "#f0593e", "#aeacd4", "#bdd630", "#4479bd", "#f5b11e"];
var footer = document.getElementById("footer");
var header = document.getElementById("header");
//helper function - get dark or lighter color
function LightenDarkenColor(col, amt) {
var usePound = false;
if (col[0] == "#") {
col = col.slice(1);
usePound = true;
}
var num = parseInt(col, 16);
var r = (num >> 16) + amt;
if (r > 255) r = 255;
else if (r < 0) r = 0;
var b = ((num >> 8) & 0x00FF) + amt;
if (b > 255) b = 255;
else if (b < 0) b = 0;
var g = (num & 0x0000FF) + amt;
if (g > 255) g = 255;
else if (g < 0) g = 0;
return (usePound ? "#" : "") + (g | (b << 8) | (r << 16)).toString(16);
}
//random new color
function GetNewColor() {
var index = Math.floor((Math.random() * 5) + 1);
return arrColor[index];
}
// set new color
function SetNewColor(color) {
document.body.style.background = color;
var NewColor = LightenDarkenColor(color, -20);
footer.style.backgroundColor = NewColor;
header.style.backgroundColor = NewColor;
//footer.style.opacity = 1.2;
}
// on document load function start
(function() {
var colorSelected = GetNewColor();
SetNewColor(colorSelected);
})();
//change color timer
window.setInterval(function() {
var colorSelected = GetNewColor();
SetNewColor(colorSelected);
}, 2000);
* {
margin: 0;
padding: 0;
}
body {
background: #bdd630;
transition: background-color 0.5s ease;
color: #fff;
}
#header {
background: #000;
height: 40px;
text-align: center;
}
#content {
/* Now, to activate scrollbars
and compensate #footer height: */
padding-bottom: 40px;
}
#footer {
background: #000;
position: fixed;
bottom: 0px;
width: 100%;
/* cause of fixed pos */
height: 40px;
text-align: center;
}
<div id="header">header</div>
<div id="content">
<p>content here</p>
</div>
<div id="footer">footer</div>
Enjoy
If you are looking for an easy to understand way to do this, check out Basecacti. Of course, Basecacti as of now does not include embedding of the background on to your own html page, so just look at the source code behind it. Here's an example if you need it:
var clr1 = renderColors("clr1");
var clr2 = renderColors("clr2");
var clr3 = renderColors("clr3");
var speed = renderColors("speed");
var deb = document.body;
var circle = 0;
deb.style.backgroundColor = clr1;
setInterval(function(){
if (circle == 0) {
deb.style.backgroundColor = clr2;
circle = 1;
}
else if (circle == 1) {
deb.style.backgroundColor = clr3;
circle = 2;
}
else {
deb.style.backgroundColor = clr1;
circle = 0;
}
}, speed);
To make this work for you, define 3 different colors as clr1, clr2, and clr3. Then set the speed variable to 2000 for 2 secs, and it should work. (The renderColors function that defines these values in the above code is what Basecacti uses to get the colors that users define from a different webpage.) Also, Basecacti is Open-Source for now, so you might want to hurry over to their site and get this code ASAP. If you only want the background to change once after 2 seconds, change the function from setInterval to setTimeout, but don't change anything else. Please comment on this post if the Basecacti website shuts down or stops working, or if I have an error in the code.

Possible: Animate Jquery slider?

Is it possible to animate the slider from jQuery? so that if I press the button the inner of the slider should move slower (for example 300ms) and also NOT to react to mouse click and slide?
This is the code:
http://jsfiddle.net/gm4tG/5/
HTML:
<div id='slider' class='sliderBar'></div>
<button>Remove 10%</button>
CSS:
html, body {
height:100%;
width:100%;
margin:0;
padding:0;
}
#slider {
height:20px;
max-height:20px;
}
.sliderBar-progress {
background:rgb(0, 255, 0);
}
JS:
$('#slider').sliderBar({
start: 100,
onChange: function (val) {
var red = 0,
green = 0;
if (val >= 50) {
red = 255 - Math.round(((val - 50) / 50) * 255);
green = 255;
} else {
red = 255;
green = Math.round(((val) / 50) * 255);
}
$('.sliderBar-progress').css({
background: "rgb(" + red + "," + green + ",0)"
});
}
});
$('button').on('click', function () {
$('#slider').setsliderBar($('#slider').getsliderBar()-10, true);
});
Thank You very much!
.sliderBar-progress {
background:rgb(0, 255, 0);
transition-duration: 5s;
-webkit-transition-duration: 5s; /* for Safari */
}
This property is supported in Chrome, Firefox, Internet Explorer 10, Opera and Safari.
Revised JSFiddle Here

Categories