How to make this Jquery-blinking background stop after a few seconds? - javascript

How to make this Jquery-blinking background stop after a few seconds? I'm trying to set the background and text to blink and then stop after 3 seconds. Thanks for your help in advance!
$(document).ready(function() {
blinkFont();
});
function blinkFont() {
document.getElementById("blink").style.color = "red"
document.getElementById("blink").style.background = "black"
setTimeout("setblinkFont()", 500)
}
function setblinkFont() {
document.getElementById("blink").style.color = "black"
document.getElementById("blink").style.background = "red"
setTimeout("blinkFont()", 500)
}
#blink {
text-align: center;
background: #000000;
color: #F00;
margin: 0;
padding: 20px;
}
#blink span {
font-size: 2em;
font-weight: bold;
display: block;
}
<div id="blink"><span>This is blinking text and background</span>
</div>

While I could think of a few more elegant ways to do this, without changing your current structure too much, you could store the Timeouts in variables and then use clearInterval , which stops a timer, to stop the recurrences after three seconds:
<script>
var intervalA;
var intervalB;
$(document).ready(function() {
blinkFont();
setTimeout(function() {
clearInterval(intervalA); clearInterval(intervalB);},3000);
});
function blinkFont() {
document.getElementById("blink").style.color = "red"
document.getElementById("blink").style.background = "black"
intervalA = setTimeout("setblinkFont()", 500);
}
function setblinkFont() {
document.getElementById("blink").style.color = "black"
document.getElementById("blink").style.background = "red"
intervalB = setTimeout("blinkFont()", 500);
}
</script>
</head>
<body>
<div id="blink"><span>This is blinking text and background</span>
</div>
</body>

You have to use SetTimeout() , SetInterval() and clearInterval() as below code.
Click Here to see working Demo
HTML
<div id="blink"><span>Demo</span>
</div>
Jquery
$(document).ready(function(){
var myVar;
myVar = setInterval(blinkFont, 500);
function blinkFont() {
var curColor = document.getElementById("blink").style.color;
var curBgC = document.getElementById("blink").style.background;
document.getElementById("blink").style.color = curColor === "red" ? "blue" : "red";
document.getElementById("blink").style.background = curBgC === "black" ? "yellow" : "black";
}
setTimeout(function () {
$("#blink").css('visibility', 'visible');
clearInterval(myVar);
}, 3000); // after 3 seconds it'll stop blinking
});
Here is Working JsFiddle - Click Here

Instead of SetTimeout use SetInterval, keep the variable with you. And keep a counter, which will be incremented after every execution, once you reach the desired number of repetition, stopinterval.
Something like this:
myVar=setInterval("javascript function", milliseconds);
//check your counter value.
window.clearInterval(myVar)

Is this fiddle satisfied you?
code :
$(document).ready(function() {
var intval;
intval = setInterval(function(){
blinkFont();
},500);
setTimeout(function() {
alert('clear');
clearInterval(intval);
}, 3000);
});
function blinkFont() {
var curColor = document.getElementById("blink").style.color;
var curBgC = document.getElementById("blink").style.background;
document.getElementById("blink").style.color = curColor === "red" ? "blue" : "red";
document.getElementById("blink").style.background = curBgC === "black" ? "yellow" : "black";
}

Related

How to pause setInterval when mouse hover?

How to pause setInterval when mouse hover ?
$(document).ready(function() {
var MyClass = $(".myclass");
if (MyClass.hover()) {
} else {
setInterval(test, 1000);
function test() {
$("#color").click();
}
}
});
This code not work!
All code in Fiddle link
Try this:
$(document).ready(function() {
var myClass = $(".myclass");
function test() {
$("#color").click();
}
var timerId = setInterval(test, 1000);
myClass.hover(
function() {
window.clearInterval(timerId);
}, function() {
timerId = setInterval(test, 1000);
}
);
});
document.getElementById('color').onclick = changeColor;
var currentColor = "red";
function changeColor() {
if(currentColor == "red"){
document.body.style.color = "green";
currentColor = "green";
} else {
document.body.style.color = "red";
currentColor = "red";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="color">
click
</button>
<div class="myclass">
Mouse Hover
</div>
<div id="myid" style="width:30px;height:30px;">
Change color
</div>

JavasScript infinitive background change with function

I'm curious if there is a way to repeat a function for as long as user stays on the page. I want function f1() to repeat changing the color of div #gallery. It's probably an infinitive loop or something, please help me.
function f1() {
setTimeout(
function() {
document.getElementById("gallery").style.backgroundColor = "blue";
}, 3000);
setTimeout(
function() {
document.getElementById("gallery").style.backgroundColor = "red";
}, 6000);
}
#gallery {
width: 500px;
height: 300px;
background-color: red;
}
<body onload="f1()">
<div id="gallery">
</div>
</body>
The previous method of using setInterval is really great, but I personally like to have a little bit more control over what happens so I use something like this for repetition:
fiddle
The 'meat and bones' is a loop like this:
const target = document.getElementById('target');
const colors = ["red", "blue", "purple", "black", "gray", "aliceblue"];
const randomColor = () => {
const randomInt = Math.floor(Math.random() * colors.length + 1);
return colors[randomInt];
}
const userStillOnPage = true;
function f1(newInterval, continueWith) {
target.style.background = randomColor();
if (userStillOnPage) {
setTimeout(continueWith || f1, newInterval || 1000);
}
}
f1();
This method makes it easy to do all kinds of things like make the loop go faster by changing the interval or even injecting a different continuation function. It's quite powerful and easily abstracted to something very generic!
You can infinitely loop your javascript with setInterval:
<html>
<head>
<style>
#gallery {
width: 500px;
height: 300px;
background-color: red;
}
</style>
</head>
<body onload="f1()">
<div id="gallery">
</div>
</body>
<script type="text/javascript">
function f1(){
setInterval(oneSecondFunction, 9000);
};
function oneSecondFunction() {
setTimeout(
function() {
document.getElementById("gallery").style.backgroundColor = "blue";
}, 3000);
setTimeout(
function() {
document.getElementById("gallery").style.backgroundColor = "red";
}, 6000);
}
</script>
</html>
document.addEventListener('DOMContentLoaded', init);
function init() {
var target = document.getElementById('gallery');
setInterval(function() {
target.style.backgroundColor = getRandomColor();
}, 1000)
// From http://stackoverflow.com/questions/1484506/random-color-generator-in-javascript
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
}

Make cursor go transparent on timer (0.5)

Here's the code, but instead of it completely disappears, is there some way to make it go 0.5 opacity? Help on this would be much appreciated.
$(function () {
var timer;
var fadeInBuffer = false;
$(document).mousemove(function () {
if (!fadeInBuffer) {
if (timer) {
console.log("clearTimer");
clearTimeout(timer);
timer = 0;
}
console.log("fadeIn");
$('.fade-object').fadeIn();
$('html').css({
cursor: ''
});
} else {
fadeInBuffer = false;
}
timer = setTimeout(function () {
console.log("fadeout");
$('.fade-object').fadeOut()
$('html').css({
cursor: 'none'
});
fadeInBuffer = true;
}, 2000)
});
});
You can use fadeTo(). Hope this helps.
$(function () {
var timer;
var fadeInBuffer = false;
$(document).mousemove(function () {
if (!fadeInBuffer) {
if (timer) {
clearTimeout(timer);
timer = 0;
}
$('.fade-object').fadeTo('slow', 1);
$('html').css({
cursor: ''
});
} else {
fadeInBuffer = false;
}
timer = setTimeout(function () {
$('.fade-object').fadeTo('slow', 0.5)
$('html').css({
cursor: 'none'
});
fadeInBuffer = true;
}, 2000)
});
});
.fade-object{
height: 300px;
background: red;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fade-object"></div>
** UPDATED **
Try using setInterval instead of setTimeout, and vary from 10 to 0 to disapear and from 0 to 10 to reapear (according to filenames).
Do this by changing trhough custom png cursors with alfas from 0 to 100 in 10 phases.
Here are some images I prepared: , , , , , , , , , , << last one is 0%
Remember that your cursor (mouse pointer) WON'T change its custom image IF it is NOT moving **, so .. you will need to translate cursor at least 10px programatically while iterating trhough the 10 images.
** UPDATE 2 **
Here you can feel the idea.
//codepen.io/jjyepez/pen/xEQAXZ
PS (forget about translating cursor .. it is not necessary whatsoever)

How do I change the colour of a div with one button using Javascript?

I am very new to Javascript so feel free to point out anything I am doing wrong. I am trying to change the colour of a div everytime a button is clicked. This is my code so far:
function setBgColour(){
if (.backgroundColor == '#ff0000'){
document.getElementsByClassName("light")[0].style.backgroundColor = '#ffff00';
} else if (.backgroundColor == '#ffff00'){
document.getElementsByClassName("light")[0].style.backgroundColor = '#00ff00'
} else if (.backgroundColor == '#00ff00'){
document.getElementsByClassName("light")[0].style.backgroundColor = '#ff0000'
}
}
window.onload = function(){
document.getElementById('next').addEventListener('click', setBgColour);
};
The problem is with your condition statements. You're doing:
if (.backgroundColor == '#ff0000')
What's the element you're looking into, to get the backgroundColor property?
You should do something like:
window.onload = function() {
var current = '#ff0000';
function setBgColour() {
var light = document.getElementsByClassName("light")[0];
if (current == '#ff0000') {
current = '#ffff00';
} else if (current == '#ffff00') {
current = '#00ff00';
} else if (current == '#00ff00') {
current = '#ff0000';
}
light.style.backgroundColor = current;
}
document.getElementById('next').addEventListener('click', setBgColour);
setBgColour();
};
.light {
width: 100px;
height: 100px;
}
<div class="light"></div>
<button id="next">Next</button>

Timed background color change

How can I change this script from jQuery to JavaScript? I have little experience with JavaScript and I don't know how to change it myself.
Script:
var rotate = function() {$("#Top")
.delay(1000).queue(function() {
$(this).css({
"background-color": "red"
});
$(this).dequeue();
})
.delay(3000).queue(function() {
$(this).css({
"background-color": "green"
});
$(this).dequeue();
})
.delay(500).queue(function(next) {
$(this).css({
"background-color": "blue"
});
$(this).dequeue();
next();
})
.queue(rotate);
};
rotate();
Html
<div id="Top"></div>
Original: http://jsfiddle.net/h4KL7/1/
John Resig is the guy who wrote jQuery and here is a blurb about How JavaScript Timers Work.
I know it is not perfect and could use setInterval() and clearInterval() to be more efficient, but this is a start DEMO
var rotate = function () {
var el = document.getElementById('Top');
setTimeout(function () {
el.style.backgroundColor = 'red';
setTimeout(function () {
el.style.backgroundColor = 'green';
setTimeout(function () {
el.style.backgroundColor = 'blue';
rotate();
}, 500);
}, 3000);
}, 1000);
}
Update: Added an array to reference timeout IDs to ensure that duplicates are not created in case time gets out of sync.
var rotate = function () {
var el = document.getElementById('Top');
var timers = new Array(3);
function red(el) {
el.style.backgroundColor = 'red';
timers[0] = setTimeout(function () { green(el); }, 1000);
clearTimeout(timers[2]);
}
function green(el) {
el.style.backgroundColor = 'green';
timers[1] = setTimeout(function () { blue(el); }, 3000);
clearTimeout(timers[0]);
}
function blue(el) {
el.style.backgroundColor = 'blue';
timers[2] = setTimeout(function () { red(el); }, 500);
clearTimeout(timers[1]);
}
red(el);
};
rotate();
The title of your post should be: "How can I change this from jQuery to CSS" ;-)
#-webkit-keyframes rainbow {
0% { background: #FFABAB; }
20% { background: #FFDAAB; }
40% { background: #DDFFAB; }
60% { background: #ABE4FF; }
80% { background: #D9ABFF; }
100% { background: #FFABAB; }
}
.top {
min-height: 200px;
-webkit-animation: rainbow 10s infinite steps(1);
}
If you want to have smooth transition between your background color just omit the steps(1) in the animation shorthand property.
Check this out!

Categories

Resources