This is my code. Here the div is animated after 5 sec and hidden after another 5 sec. I need to repeat this every 5 sec. That means every 5 second the div will animate and disappear after another 5 second.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript" src="jquery.animate-colors.js"></script>
<script type="text/javascript" src="jquery.animate-colors.min.js"></script>
<script>
$(window).load(function(){
$('#div').delay(5000).fadeIn(function() {
$(this).text('Some other text!').css({'text-align':'center',})
});
$("#div").animate({
left:'450px',
opacity:'0.5',
height:'250px',
width:'250px',
border:'3px solid',
borderColor: 'darkolivegreen',
backgroundColor: '#cccc'
})
$('#div').delay(5000).fadeOut();
});
</script>
</head>
<body>
<div id="div" style="background:#98bf21;height:100px;width:100px;position:absolute;">Please login</div>
</body>
</html>
You could use the setInterval() method in javascript.
Summary
Calls a function or executes a code snippet repeatedly, with a fixed
time delay between each call to that function.
MDN Documentation
I've just wrapped your code in the "fader" function, then on document load, setInterval will run every 10 seconds.
<script>
function fader () {
$('#div').delay(5000).fadeIn(function() {
$(this).text('Some other text!').css({'text-align':'center',})
});
$("#div").animate({
left:'450px',
opacity:'0.5',
height:'250px',
width:'250px',
border:'3px solid',
borderColor: 'darkolivegreen',
backgroundColor: '#cccc'
})
$('#div').delay(5000).fadeOut();
};
$(function () {
setInterval(fader,10000);
})
</script>
<div id="blinkText"></div>
<script>
// Takes text to blink and id of element to blink text in
function blinkText(text, id) {
// Blink interval
setInterval(blinker, 5000);
// Flag to see what state text is in (true or false)
var flag = true;
// Number of times to blink text
var blinkNum = 10000;
var i = 1;
//you can select whole div by ajax
var divID = document.getElementById(id);
function blinker() {
if (i < blinkNum) {
if (flag) {
divID.innerHTML = text;
flag = false;
} else {
divID.innerHTML = "";
flag = true;
}
i++;
} else {
// Delete if it's still showing
divID.innerHTML = "";
// Stop blinking
clearInterval(blinker);
}
}
}
blinkText("Hello World", "blinkText");
</script>
Related
I have a question about my code. What I'm trying to do is if a certain button is clicked and it isn't clicked again within 4 seconds, a element will be showed and another element hide. But if it is clicked within 4 seconds, it stays the same and so on. I think I should use SetInterval() and ClearInterval(). Currently I have two other functions that do other things. Maybe I can my function there?
Hopefully I have made it clear.
Current javascript code:
var clicks = 0;
function clicks5times() {
clicks = clicks+1;
if(clicks == 6){
document.getElementById('scherm3').style.display = 'block';
document.getElementById('scherm2.2').style.display = 'none';
}
}
var clicked = false;
setInterval(function(){
if (!clicked) {
document.getElementById("scherm4").style.visibility = "visible";
document.getElementById("scherm2.2").style.visibility = "hidden";
}
},13000);
document.getElementById("buttontimer").addEventListener("click", function(){
clicked = true;
});
Rather than set interval, I would say a timer would be better. Eg:
var clickTimer;
function startTimer() {
clickTimer = window.setTimeout(function(){
document.getElementById("scherm4").style.visibility = "visible";
document.getElementById("scherm2.2").style.visibility = "hidden";
},4000);
}
function stopTimer() {
window.clearTimeout(clickTimer);
}
function restartTimer() {
stopTimer();
startTimer();
}
document.getElementById("buttontimer").addEventListener("click", function(){
restartTimer();
});
This way when you want to stop the timer or start the timer, you have to just call above functions for other scenarios.
eg:
If you have an init function:
function init() {
...
//some code
startTimer();
}
And maybe call stop timer like so:
function clicks5times() {
...
stopTimer();
}
Split your event handlers in two different functions (eg firstClick and secondClick). The first handler should just add a second event listener and remove it after 4 seconds. For this one-off task, use setTimeout instead of setInterval as you need the task to be done only once after 4 seconds and not every 4 seconds. So I would proceed as follows:
var secondClick = function() {
// DO WHATEVER YOU WANT TO HAPPEN AFTER THE SECOND CLICK
}
var firstClick = function() {
// DO WHATEVER YOU WANT TO HAPPEN AFTER THE FIRST CLICK
document.getElementById("buttontimer").addEventListener("click", secondClick);
setTimeout(function() {
document.getElementById("buttontimer").removeEventListener("click", secondClick);
}, 4000);
};
buttonElement.addEventListener("click", firstClick);
in Javascript
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<button id="buttontimer">fghfgh</button>
</body>
</html><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<button id="buttontimer">fghfgh</button>
<script>
document.getElementById('buttontimer').onclick = function(){
document.getElementById("buttontimer").disabled=true;
setInterval(function(){
if (document.getElementById("buttontimer").disabled == true) {
document.getElementById("buttontimer").disabled = false;
}
},10000);
};
</script>
</body>
</html>
and Jquery
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var button = $('<button>Click Me</button>');
button.clicked = false;
$('body').append(button);
var clicked = false;
button.click(function(){
button.clicked = true;
button.prop('disabled', true);
clicked = true
setInterval(function(){
if (clicked) {
button.prop('disabled', false);
}
},10000);
});
});
</script>
</head>
<body>
</body>
</html>
once u click button disable the property after the timer finish enable back the property
I am trying to highlight each menu items after 1 sec gap.
It works fine, but I am facing a problem for the last menu item. I added
$(strtemp).removeClass("change"); for clearing the last menu item, but that line is getting executed before the setInterval function gets executed. I am not able to understand why?
my.js
$(document).ready(function(){
$(".parent").click(function(){
str = "li:nth-child(";
strtemp="";
i=1;
var refreshID=setInterval(function(){
str1=str.concat(i);
str1=str1.concat(")");
str2=str.concat(i-1);
str2=str2.concat(")");
if($(str2).hasClass("change")){
$(str2).removeClass("change");
}
$(str1).addClass( "change" );
if(i==10){
strtemp=str1;clearInterval(refreshID);
}
i++;
}, 1000);
$(strtemp).removeClass("change");
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<script type="text/Javascript" src="jquery.js"></script>
<script src="my.js"></script>
<title>My Jquery</title>
</head>
<body>
<div class="parent">
<ol>
<li>AAAAA</li>
<li>AAAAA</li>
<li>AAAAA</li>
<li>AAAAA</li>
<li>AAAAA</li>
<li>AAAAA</li>
<li>AAAAA</li>
<li>AAAAA</li>
<li>AAAAA</li>
<li>AAAAA</li>
</ol>
</div>
</body>
</html>
stylesheet.css
.parent{
background-color: yellow;
height:200px;
width:400px;
}
.change{
border: 1px dotted green;
background-color: red;
height:15px;
width:100px;
}
The $(strtemp).removeClass call is outside the callback function passed to setInterval. The code inside the function will execute each tick, everything outside will be executed sequentially when the click handler fires.
Edit
Are you looking for something like: http://jsfiddle.net/qprjqy2n/ ?
$(document).ready(function(){
$(".parent").click(function(){
str = "li:nth-child(";
strtemp="";
i=1;
var refreshID=setInterval(function(){
str1=str.concat(i);
str1=str1.concat(")");
str2=str.concat(i-1);
str2=str2.concat(")");
if($(str2).hasClass("change")){
$(str2).removeClass("change");
}
$(str1).addClass( "change" );
if(i==11){
strtemp=str1;clearInterval(refreshID);
$(strtemp).removeClass("change");
}
i++;
}, 100);
});
});
I would be interested to know what your overall goal is as there would almost certainly be a more straightforward approach.
You can do with also as:
function atlast(strtemp)
{
$(strtemp).removeClass("change");
}
$(document).ready(function(){
$(".parent").click(function(){
str = "li:nth-child(";
strtemp="";
i=1;
var refreshID=setInterval(function(){
str1=str.concat(i);
str1=str1.concat(")");
str2=str.concat(i-1);
str2=str2.concat(")");
if($(str2).hasClass("change")){
$(str2).removeClass("change");
}
$(str1).addClass( "change" );
if(i==10){
strtemp=str1;clearInterval(refreshID);
atlast(strtemp);
}
i++;
}, 1000);
});
});
As a suggestion, much easier approach:
$(".parent").click(function() {
lis = $(this).find('li');
i = -1;
inter = setInterval(function() {
if (i < lis.length - 1) {
i++;
$(lis[i - 1]).removeClass('change');
$(lis[i]).addClass('change');
console.log($(lis[i]).text() + '_________________' + i);
} else {
console.log('end');
$(lis[i]).removeClass('change');
clearInterval(inter);
}
}, 1000);
});
without building of css selectors, and corrected timer, and fiddle link... http://jsfiddle.net/Lb6v334a/1/
You can use nested setTimeout functions, the answer below is inspired from this SO post ..
$(document).ready(function(){
$(".parent").click(function(){
items = $(this).find('li');
i = -1;
len = items.length;
function animation_loop() {
$(items[i]).addClass('change');
setTimeout(function(){
$(items[i]).removeClass('change');
}, 100 );
setTimeout(function() {
if (i < len)
{
i++;
animation_loop();
}
}, 100);
};
animation_loop();
});
});
Demo
You can also do it as below
var index=1;
var curretInterval;
$(".parent").click(function(){
clearInterval(curretInterval);
curretInterval=setInterval(function(){
$("ol li:nth-child("+(index-1)+")").removeClass("change");
$("ol li:nth-child("+index+")").addClass("change");
index=index+1;
index=index>11?1:index;
},1000);
});
JSFiddle for the same is
http://jsfiddle.net/prasadFiddle/405cnu39/23/
and on next clicks if you want to start highlighting from begining then http://jsfiddle.net/prasadFiddle/405cnu39/24/
If you want to run this loop only once then http://jsfiddle.net/prasadFiddle/405cnu39/25/
I would like to hide and then show the "Reset" button as soon as the counter reaches zero.
Index.html:
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script type="text/javascript" src="countdown.js"></script>
</head>
<body>
<input type="text" id="timer">
<script type="text/javascript">
timer = new Countdown();
timer.init();
</script>
<button id="reset">Reset</button>
<script type="text/javascript">
$("#reset").click(function(){
//timer = new Countdown();
timer.reset();
});
</script>
</body>
</html>
Please see http://jsfiddle.net/orokusaki/o4ak8wzs/1/ for countdown.js
AWolf's answer is a bit fancier than mine, and they made some good points about your code, but I tried to keep mine simple and tried not to change your original code too much.
Your init() function will now hide the Reset button, and I had the update_target() function show the Reset button when the timer expired.
Fiddle: http://jsfiddle.net/rgutierrez1014/o4ak8wzs/4/
In this jsFiddle you'll find the updated code and how you could add that behaviour.
I've also improved your code a bit. It's easier to write Countdown.prototype = { init: function() {...}, ...} then writing Countdown.prototype.init = function() {...}
I also changed your setInterval to setTimeout and start a new timeout every second. That's easier and you don't need to clear the interval at the end. Also the callback function for your interval seemed a bit strange and that probably won't work.
You could add your click handlers in the init method of your countdown object like this $('#start').click(this.start.bind(this)); the .bind(this) is used to change the context inside the click handler to the currently used object. Then this inside of the handler is your object and you can access everything with this.
To hide the reset button at start I've used the css display: none; and if you are at zero then show the button with $('#reset').fadeIn('slow'); or $('#reset').show(); if you don't want the animation.
Update 13.03.2015
As mentioned in the comments I've improved the code and now I'm using a jQuery Countdown plugin.
Please have a look at the latest version in this jsFiddle.
I think it's much better then the other code.
(function () {
function Countdown() {
this.start_time = "00:30";
this.target_id = "#timer";
//this.name = "timer";
}
Countdown.prototype = {
init: function () {
console.log('init called');
this.reset();
$('#start').click(this.start.bind(this));
$('#reset').click(this.reset.bind(this));
},
reset: function () {
time = this.start_time.split(":");
//this.minutes = parseInt(time[0]);
this.seconds = parseInt(time[1]);
this.update_target();
},
tick: function () {
if (this.seconds > 0) //|| this.minutes > 0)
{
if (this.seconds == 0) {
// this.minutes = this.minutes - 1;
this.seconds = 59
} else {
this.seconds = this.seconds - 1;
}
this.start();
}
else {
// show reset button
$('#reset').fadeIn('slow');
}
this.update_target();
},
start: function() {
console.log('start called');
//setTimeout(this.name + '.tick()', 1000);
setTimeout(this.tick.bind(this), 1000);
},
update_target: function () {
seconds = this.seconds;
if (seconds < 10) seconds = "" + seconds;
$(this.target_id).val(this.seconds);
}
};
var counter = new Countdown();
counter.init();
})();
#reset {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="timer">
<button id="start">Start</button>
<button id="reset">Reset</button>
I'm doing preload page. Here my code:
<style>
#page-preloader { ... }
#page-preloader .spinner { ...}
</style>
<script src="js/jquery.js"></script>
<script>
$(window).on('load', function () {
var $preloader = $('#page-preloader'),
$spinner = $preloader.find('.spinner');
$spinner.fadeOut();
$preloader.delay(350).fadeOut('slow');
});
</script>
</head>
<body>
<div id="page-preloader"><span class="spinner"></span></div>
...
All good, but i want to make some condition, and don't know how do it.
I need to preloader work minimum 4 second (even if page load for 1 sec) if session is empty.
Increase delay().
<script>
$(window).on('load', function () {
var $preloader = $('#page-preloader'),
$spinner = $preloader.find('.spinner');
$spinner.fadeOut();
$preloader.delay(3000).fadeOut('slow');
});
According to this thread: how many javascript setTimeout/ setInterval call can be set simultaneously in one page? it is possible to have multiple setIntervals at the sametime.
However, is it possible to have a setInterval and setTimeout at the sametime?
This is not working...
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
init();
});
function init() {
$('#startbutton').on('click', handleClick);
}
</script>
</head>
<body>
<script>
var playBeep = function () {
var snd = new Audio("beep-7.wav");
snd.play();
}
var handleClick = function () {
var interval1 = setInterval(updateDisplay, 1);
makeIntervals([1,2,3], playBeep);
}
var makeIntervals = function(timeList,callback){
intervals = []
for(i in timeList){
intervals.push(setTimeout(callback,timeList[i]))
}
return intervals
}
function updateDisplay() {
var value = parseInt($('#timer').find('.value').text(), 10);
value++;
$('#timer').find('.value').text(value);
}
</script>
<button type="button" id="startbutton">Play Beep</button>
<P>
<div id="timer"><span class="value">0</span> ms</div>
<P>
Of course. However just make sure you don't have too many.