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;
}
}
Related
I'm working on a progress bar. It has a label. I want to adjust that label a certain script is finished. After finding some answers of probable solution, I came up with the following script. The first initiates and works as expected. However, the second one doesn't. What's wrong with it? Here's the code:
HTML:
<form method ="post">
<input class=generate type="submit" value="Upload" onclick="move();finalize()"/>
</form>
Javascript:
<script>
function move() {
var elem = document.getElementById("myBar");
var myFunc01 = function() {
var i = 1;
while (i < 101) {
(function(i) {
setTimeout(function() {
i++;
elem.style.width = i + '%';
elem.innerHTML = i + '%';
}, 600 * i)
})(i++)
}
};
myFunc01();
}
</script>
<script>
function finalize() {
var elem = document.getElementById("myBar");
var myFunc02 = function() {
elem.innerHTML = 'Finalizing...';
};
setTimeout(myFunc02, 600);
}
</script>
var elem = document.querySelector('#myBar');
function done() {
elem.innerText = 'UPLOAD HAS FINISHED';
}
var upload = function(callback) {
var width = 1;
var id;
var frame = function() {
if (width >= 100) {
clearInterval(id);
callback();
} else {
width++;
elem.style.width = width + '%';
}
};
id = setInterval(frame, 10);
};
/*
upload(function() {
elem.innerText = 'UPLOAD HAS FINISHED';
});
*/
#myProgress {
width: 100%;
background-color: grey;
}
#myBar {
width: 1%;
height: 30px;
background-color: green;
text-align: center;
line-height: 27px;
}
<button onclick="upload(done)">START UPLOAD</button>
<div id="myProgress">
<div id="myBar"></div>
</div>
You could use a callback. A callback is a function that runs upon completion.
function move(callback) {
//code you want to happen first
}
move(function(){
//code you want to have happen after completion
})
thats the basic idea of how a simple callback works
Thanks James, that's it!
After some re-arranging, this is what the second script looks like. And it works as expected.
<script>
function finalize() {setTimeout(function(){
var elem = document.getElementById("myBar");
var myFunc02 = function() {
elem.innerHTML = 'Finalizing...';
};
myFunc02();
}
, 600);}
</script>
Here is a little story... I want to make a for loop that makes make 's to addenventlisteners so when I move over :hover/onmouseover it should shift bewteen 2 colors. But I can not figure out how I get the keyword down to the function redB ...
But I dont know if I am on the rigth way...
$(document).ready(function() {
var i;
for (i = 0; i < 10; i++) {
document.getElementById("sek2" + i + ).addEventListener("mouseover", Over(this));
document.getElementById("sek2" + i + ).addEventListener("mouseout", Out(this));
}
});
function greyB(x) {
x.style.backgroundColor = "grey";
}
function redB(x) {
x.style.backgroundColor = "red";
}
Using vanilla javascript, close to your current code, this is as easy as:
var i;
for (i = 0; i < 1; i++) {
document.getElementById("sek2" + i).addEventListener("mouseover", function(){ greyB(this); });
document.getElementById("sek2" + i).addEventListener("mouseout", function(){ redB(this); });
}
function greyB(x) {
x.style.backgroundColor = "grey";
}
function redB(x) {
x.style.backgroundColor = "red";
}
<div id="sek20">Mouse over me</div>
If using jQuery this is even easier:
$("[id^='sek2']").on('mouseover', function(){
$(this).css('background-color','grey');
}).on('mouseout',function(){
$(this).css('background-color','red');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sek20">Mouse over me</div>
you are calling the wrong function name and if you use $(document).ready() you need ah jquery library
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Js code
$(document).ready(function() {
var i;
for (i = 0; i < 10; i++) {
document.getElementById("sek2" + i + ).addEventListener("mouseover", greyB);
document.getElementById("sek2" + i + ).addEventListener("mouseout", redB);
}
});
function greyB() {
this.style.backgroundColor = "grey";
}
function redB() {
this.style.backgroundColor = "red";
}
Is something like this what you looking for?
$(document).ready(function() {
var i;
for (i = 0; i < 10; i++) {
let newDiv = document.createElement('div');
newDiv.classList.add('square');
newDiv.addEventListener("mouseover", greyB);
newDiv.addEventListener("mouseout", redB);
document.querySelector('body').appendChild(newDiv);
}
});
function greyB() {
this.style.backgroundColor = "grey";
}
function redB() {
this.style.backgroundColor = "red";
}
.square {
background-color: red;
width: 100px;
height: 100px;
margin: 10px;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I ended with this solution, but can anyone tell there to go getting more information about this code. What kind of language maybe a link to some place. So I not getting different code to play with futher.
Thanks...
var i;
for (i = 0; i < 1; i++) {
document.getElementById("sek2" + i).addEventListener("mouseover", function(){ greyB(this); });
document.getElementById("sek2" + i).addEventListener("mouseout", function(){ redB(this); });
}
function greyB(x) {
x.style.backgroundColor = "grey";
}
function redB(x) {
x.style.backgroundColor = "red";
}
<div id="sek20">Mouse over me</div>
Hi I finally got my progress bar the way I want, is there a way to make it have delay spikes? like its actually loading data, for now this is just for looks on my website but I would like it to look authentic. heres the code. the max delay I would need and want is 500 milliseconds.
<html><head>
<style>
#adLinkb,
#adLinkb2 {
font-size: 12px;
color: #fff;
font-family:sans-serif;
}
</style>
</head>
<body>
<div id="adLinkb" style="border: 1px solid black;width:212;background-color:black;border-color:white"></div>
<br>
<div id="adLinkb2" style="border: 1px solid black;width:212;background-color:black;border-color:white"></div>
<script type="text/javascript">
function buildBar(id, callback) {
var currentAdb = 0;
var imgCtb = 70;
function cycleb() {
var output = '';
for (var i = 0; i < imgCtb; i++) {
output += i > currentAdb ? ' ' : '/';
}
output += '';
document.getElementById(id).innerHTML = output;
++currentAdb;
if (currentAdb == imgCtb) {
window.clearInterval(myInterval);
if (typeof callback == 'function') {
callback();
}
}
}
var myInterval = window.setInterval(cycleb, 100);
}
function callback1() {
buildBar('adLinkb2', callback2);
}
function callback2() {
//window.location... stuff here
alert('redirect should go here');
}
buildBar('adLinkb', callback1);
</script>
</body></html>
You can replace the setInterval with a setTimeout and re-schedule with a random timeout
window.setTimeout(cycleb,10+Math.random()*300);
the fiddle: http://jsfiddle.net/martijn/qqf90r3f/
alternative spike:
if(Math.random()>0.9)
{
// 10% change on a spike
window.setTimeout(cycleb,10+Math.random()*1000);
}
else{
window.setTimeout(cycleb,10+Math.random()*10);
}
http://jsfiddle.net/martijn/qqf90r3f/1/
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";
}
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!