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!
Related
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;
}
}
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)
originally I'm using jquery fade in and fade out to do blinking for a fixed number of times like below:
function blink(selector, counter) {
$(selector).fadeOut(500, function() {
$(this).fadeIn(500, function() {
if (counter++ < 10) {
blink(this, counter);
}
});
});
}
Now I want to change it to using jquery to change the background color to do blinking effect. But my coding don't seems to work:
function blink(selector, counter) {
setTimeout(function() {
$(selector).css("background-color", "red");
}, 500);
setTimeout(function() {
$(selector).css("background-color", "black");
}, 500);
if (counter++ < 10) {
blink(this, counter);
}
}
It just blink for once. Anything wrong guys?
I try the below but doesn't work too:
function blink(selector, counter) {
setTimeout(function() {
$(selector).css("background-color", "red", function() {
setTimeout(function() {
$(this).css("background-color", "black", function() {
if (counter++ < 10) {
blink(this, counter);
}
});
}, 1000);
});
}, 1000);
}
Any ideas guys?
You are calling blink recursively but there is no callback for when the timeout finishes so it is adding all of the timeout events at the same time instead of one after the other (well not exactly the same time but you get the idea).
You can try it this way:
function blink(selector, counter) {
setTimeout(function() {
if( $(selector).hasClass('black') ) {
$(selector).removeClass('black').addClass('red');
} else {
$(selector).removeClass('red').addClass('black');
}
if( counter++ < 10 ) { // to get the result you want this number may need to be 20 for 10 blinks
blink(selector, counter);
}
}, 500);
}
I would set the classes black and red to utilize the background color.
UPDATE
Your second example fails because jQuery doesn't accept a callback function as an argument for the css method. So doing the following won't log anything to the console:
$('.my-element').css('background', 'red', function() {
console.log('this will not log anything because jquery does not call this callback function');
});
For background color animation you would probably need jquery-ui library or you could use css animation to do this:
function blink(selector) {
$(selector).addClass('aniBg');
}
blink("div");
.aniBg {
width: 200px;
height: 200px;
background-color: red;
border: solid 1px black;
animation: animeBG 2s 5;
-webkit-animation: colorchange 2s 5;
}
#keyframes animeBG {
0% { background: red; }
100% { background: black; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>color animation</div>
Fiddle.
$(document).ready(function() {
function blink(selector, counter) {
var t = counter * 1000;
setTimeout(function() {
$(selector).css("background-color", "red");
}, t);
setTimeout(function() {
$(selector).css("background-color", "black");
}, t + 500);
if (counter++ < 10) {
blink(selector, counter);
}
}
blink($('div'), 1);
});
div {
width: 50px;
height: 50px;
border: 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>
this may work for your need
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";
}
I have this animation that makes some buttons on screen 'beat'. It works fine exept one thing, the animation is too 'sharp' and not smooth, how can I smooth it?
function myFunction() {
setInterval(function () {
tstFnc();
}, 1000);
}
var flag = true;
function tstFnc() {
var numM = Math.floor((Math.random() * 10) + 1);
var stringM = '#mgf_main' + numM + ' img';
$(stringM).animate({
width: '80px',
height: '80px'
}, 150, function () {
$(stringM).animate({
width: '68px',
height: '68px'
}, 150, function () {
// nothing
});
});
};
You can set the easing property on the animate options.
http://api.jquery.com/animate/
http://easings.net/
Try this here, animatethis is a function and target element is the id of element and speed is depend on you.. and marginleft is a example, you should try your code.
function animatethis(targetElement, speed) {
$(targetElement).animate({ width: "+=10px", height: "+=10px"},
{
duration: speed,
complete: function () {
targetElement.animate({width: "+=10px", height: "+=10px" },
{
duration: speed,
complete: function () {
animatethis(targetElement, speed);
}
});
}
});
}