jquery blink a few - javascript

i want to give blink effect to an element by using addClass and removeClass 3 times each
i tried this
$("#div").addClass("orange").delay(300).queue(function(next){
$(this).removeClass("orange");
next();
});
this is works just 1 time
how can i make this happened 3 times with 300 ms delay?

Just count to three:
(function() {
var count = 0, $div = $('#div'), interval = setInterval(function() {
if ($div.hasClass('orange')) {
$div.removeClass('orange'); ++count;
}
else
$div.addClass('orange');
if (count === 3) clearInterval(interval);
}, 300);
})();
You could get fancy and write your own animation plugin for it, I guess.

Related

stop javascript loop, setTimeout

This animation should stop playing (stop snowing) after 10 seconds. I added a function to the bottom, but it actually starts the animation after 10 seconds, rather than stopping the animation after 10 seconds.
I only want it to play for 10 seconds total time, and start right-away, see my codePen to see what I mean.
setTimeout(function() {
createSnow(20);
loop();
}, 10000)
here is a codePen to see what I mean:
https://codepen.io/celli/pen/XzzjRW
You were close. You just needed a way to tell the system to stop the animation loop. See my codepen: https://codepen.io/intervalia/pen/zPPoBZ
I added a variable to indicate if animation should be happening:
var animating = true;
A routine to stop the animation:
function stopAnimation() {
animating = false;
//Add something in here to clear the screen
}
A validation check in the animation loop:
function loop() {
if (animating) {
draw();
update();
animFrame(loop);
}
}
And changed your timeout to turn off the animation:
createSnow(150);
loop();
setTimeout(stopAnimation, 10000);
Cool animation!!
What you'll want to do is create a "timer", finding the difference between when you started and the current time.
I'm not sure if you wanted createSnow(20) inside of the loop or not, so I put it before, as initialization.
createSnow(20);
const start = new Date();
while(new Date() - start < 10000) {
loop();
}
Use cancelAnimationFrame.
Sample usage
Declare cancelAnimFrame:
var cancelAnimFrame =
window.cancelAnimationFrame ||
window.mozcancelAnimationFrame ||
window.webkitcancelAnimationFrame ||
window.mscancelAnimationFrame;
Update loop function:
var animId;
function loop() {
draw();
update();
animId = animFrame(loop);
}
and use animId to stop animation.
(As already mentioned, starting snowing should be out of setTimeout.)
createSnow(20);
loop();
setTimeout(function() {
cancelAnimFrame(animId)
}, 1000)
the only thing that you have to change is a little change of your code plz see this code below :
var timeOut = setTimeout(function() {
createSnow(20);
loop();
}, 10000);
clearTimeout(timeOut);

Allowing for maximum number of opened accordion sections using jQuery

I've looked all over the internet and I can't seem to find a good way to do this.
I've got an accordion menu that I've built primarily using addClass/removeClass and css. It has special functionality, the accordion tabs open after a delay on mouseover and they open and close on click. I can currently open all of them at once, but I'd like to limit this to 2 or 3 with the earliest selected panel closing after I hit that limit. So I'd either need to make the classes numbered and switch them on every action, or perhaps apply a variable that keeps track of the order in which the panels were selected and switch them.
Below is the code I have so far. I've only been able to get as far as keeping count of how many tabs there currently are open. Does anyone have an idea as to what the best way to approach this is?
var timer;
var counter = 0;
$('li.has-dropdown').mouseenter(function() {
dd_item = $(this);
if(!$(this).hasClass('expand-tab')){
timer = setTimeout ( function () {
$(dd_item).addClass('expand-tab');
counter++;
}, 200);
};
}).mouseleave(function(){
clearTimeout(timer);
console.log(counter);
}).click(function() {
if ($(this).hasClass('expand-tab')){
$(this).removeClass('expand-tab');
counter--;
console.log(counter);
}else{
$(this).addClass('expand-tab');
console.log(counter);
}
});
Add a incrementting data-index to each opened tab.
count the tabs on the end of the hover effect, if they are to many, sort them by the index, and hide the lowest/oldest.
var timer;
var index = 1;
$('li.has-dropdown').mouseenter(function() {
dd_item = $(this);
if(!$(this).hasClass('expand-tab')){
timer = setTimeout ( function () {
$(dd_item).addClass('expand-tab');
$(dd_item).attr('data-index', index++);
counter++;
}, 200);
};
}).mouseleave(function(){
clearTimeout(timer);
console.log(counter);
}).click(function() {
$(this).taggleClass('expand-tab'); // see jQuery toggleClass();
$(this).attr('data-index', index++);//this will add index on closed tabs also.. but it does not matter at the end.
});
if($('.expand-tab').length> 3){
//custom inline sorting function.
var expanded_tabs = $('.expand-tab').sort(function (a, b) {
return (parseInt( $(a).attr('data-index')) < parseInt( $(b).attr('data-index')) ? -1 : 1 ;
});
//time out .. effect etc.
expanded_tabs[0].removeClass('expand-tab');
}
P.S I don't like havving Hover and Click in the same place ... try to separate the events and call a unified collapseIfToMany function in on each event
This is a corrected version. I decided to use a variable for the maximum panels opened, this way you don't have to dig if you decide you want to change it, or if you add more to the code.
var timer;
var index = 1;
var maxOpen = 2;
$('li.has-dropdown').mouseenter(function() {
dd_item = $(this);
if(!$(this).hasClass('expand-tab')){
timer = setTimeout ( function () {
$(dd_item).addClass('expand-tab');
$(dd_item).attr('data-index', index++);
collapseIfTooMany();
}, 200);
};
}).mouseleave(function(){
clearTimeout(timer);
}).click(function() {
$(this).toggleClass('expand-tab'); // see jQuery toggleClass();
$(this).attr('data-index', index++);//this will add index on closed tabs also.. but it does not matter at the end.
});
function collapseIfTooMany(){
if($('.expand-tab').length > maxOpen){
//custom inline sorting function.
var expanded_tabs = $('.expand-tab').sort(function (a, b) {
return (parseInt( $(a).attr('data-index')) < parseInt( $(b).attr('data-index'))) ? -1 : 1 ;
});
//time out .. effect etc.
$(expanded_tabs[0]).removeClass('expand-tab');
}
};

Duplicated countdown timer after click event

I have this function:
var secondsRemaining = 45;
function countdown(secondsRemaining) {
var seconds = secondsRemaining;
if (secondsRemaining > 0) {
$('.timer > div').html(seconds);
secondsRemaining--;
} else {
if (secondsRemaining == 0) {
// Times up ....
}
}
setInterval(function() {
countdown(secondsRemaining);
}, 1000);
}
I am running the function in the Document ready function with:
countdown(secondsRemaining);
and also I run it again after I clicked for answer.
the problem is that I have 2 countdown timer now running simultaneously, new one that start from 45 seconds and the old one that continue from where it was.
Use clearInterval()
First, store the interval id of the first setInterval():
var secondsRemaining = 45;
function countdown(secondsRemaining) {
var seconds = secondsRemaining;
if (secondsRemaining > 0) {
$('.timer > div').html(seconds);
secondsRemaining--;
} else {
if (secondsRemaining == 0) {
// Times up ....
}
}
myinterval=setInterval(function() { //myint now contains the interval id
countdown(secondsRemaining);
}, 1000);
}
Now, when the user clicks, before setting up a new interval, cancel the first one with clearInterval():
button.onclick=function(){
//do stuff
clearInterval(myinterval)
setInterval(function() {
countdown(secondsRemaining);
}, 1000);
// do stuff
}
Sorry I don't really understand the way you have phrased the question seems to say that you intentionally want to start two time events, one when the document has loaded and the other when you click answer which are both outputting to the same element.
If the problem is you want it to have the output in two different elements then you could pass an argument of the element you could use:
countdown($('.pick-me'), secondsRemaining);
If you want to use the same element, then you could always clear the interval on each click and then set the interval for the new event, just got the update and seen Manishearths response so wont go into any more detail about it as that's probably the answer you are looking for.

jQuery/JavaScript timer

I have a simple function that I wrote that transitions three div elements using a fade in/out effect. The event is triggered when a user clicks a link. Here's my code:
$(".link1").click(function () {
$(".feature1").fadeIn(1000);
$(".feature2").fadeOut(1000);
$(".feature3").fadeOut(1000);
});
$(".link2").click(function () {
$(".feature1").fadeOut(1000);
$(".feature2").fadeIn(1000);
$(".feature3").fadeOut(1000);
});
$(".link3").click(function () {
$(".feature1").fadeOut(1000);
$(".feature2").fadeOut(1000);
$(".feature3").fadeIn(1000);
});
I need to be able to set some sort of timer so that these transitions happen automatically every 8 seconds or so. I also want them to "loop" essentially, so that if we get to the third div in the set, it returns to the first div.
Try using setTimeout() function.
var timer = null;
function foo_loop(div, timeout) {
if (div > 3) div = 1;
$(".feature"+div).fadeIn(1000);
$("div[class^=feature]:not(.feature"+div+")").fadeOut(1000);
clearTimeout(timer);
timer = setTimeout(function() {
foo_loop(div + 1, timeout);
}, timeout);
}
Run this like that (To start with first div and 8 second timeout):
foo_loop(1, 8000);
Function for stopping loop:
function stop_loop() {
clearTimeout(timer);
}
Run it when you need to stop the loop (for example on click on element with id="stop"):
$('#stop').bind('click', stop_loop);
setInterval(expression, timeout); runs the function in intervals, with the length of the timeout between them
example:
var intervalID = setInterval(alert('heelo'), 3000); // will alert hello every 3 seconds
// clearInterval(intervalID); // will clear the timer
Try the following:
var i = 0;
var transition = setInterval(function(){
i++;
if (i == 4) {i = 1}
$(".feature"+i).stop().fadeIn(1000, function(){
$(this).delay('6000').fadeOut(1000)
})
}, 8000)
not sure I fully understand when you want them to loop or how often, but I think this should help you out a bit... every 8 seconds it loops through the animations...
function fadeLoop(selectors, animations, times, index) {
index = index || 0;
if(index == selectors.length) return;
$((selectors[index])[animations[index]](times[index], function() {
fadeLoop(selectors, animations, times, index + 1);
});
}
setInterval(function() {
fadeLoop(
['.feature1', '.feature2', '.feature3'],
['fadeIn', 'fadeOut', 'fadeOut'],
[1000, 1000, 1000]
);
fadeLoop(
['.feature1', '.feature2', '.feature3'],
['fadeOut', 'fadeIn', 'fadeOut'],
[1000, 1000, 1000]
);
fadeLoop(
['.feature1', '.feature2', '.feature3'],
['fadeOut', 'fadeOut', 'fadeIn'],
[1000, 1000, 1000]
);
}, 1000 * 8);

Stopping increment at specific height

I am animating images within a logo in a slot-machine type of animation. I need it to stop animating once it gets to the top of the image (and send a callback if possible).
Currently, this is how I'm accomplishing the animation:
window.setInterval(function() {
$('#title-1 img').animate({bottom : '-=60px'})
}, 5000);
Any ideas on how I would get it to stop, and to send the callback?
So I assume you have a sprite image containing multiple logos, you want them to slide each 5 seconds until you reach the last one, and then call the callback?
var cnt = 6,
$img = $('#title-1 img'),
i = 0;
function animate_logo(cb) {
if (i < cnt) {
$('#title-1 img').animate({bottom : '-=60px'});
i += 1;
setTimeout(function () {animate_logo(cb)}, 5000);
}
else {
cb();
}
}();
var interval = window.setInterval(function() {
$('#title-1 img').animate({bottom : '-=60px'},
function(){
if(`some stop point`) clearInterval(interval);
}
);
}, 5000);
I would not suggest using a setInterval when dealing with animations due to the way newer browsers are making changes to the way setInterval and setTimeout work when the tab is not the active tab.
var $title1 = $("#title-1");
var $title1img = $title1.find('img');
function anim(){
if ($title1.height() < parseInt($title1img.css("bottom"))) {
setTimeout(function(){
$title1img.animate({bottom : '-=60px'},anim);
},5000);
}
}
$title1img.animate({bottom : '-=60px'},anim);
Edit: another reason not to use setInterval to fire off animations is due to the reqeustAnimationFrame that was implemented in 1.6 and removed in 1.6.3, which will more than likely be added back in 1.7. If you write code now that will be compatible later, that's less maintenance you will have to do later if you end up being required to upgrade.
Here's a jsfiddle http://jsfiddle.net/czUnU/
Edit: function...
function animColumn(title,img){
function anim(){
if (title.height() < parseInt(img.css("bottom")) {
setTimeout(function(){
img.animate({bottom : '-=60px'},anim);
},5000);
}
}
img.animate({bottom : '-=60px'},anim);
}
animColumn($("#title-1"),$("#title-1 img"));
animColumn($("#title-2"),$("#title-2 img"));
animColumn($("#title-3"),$("#title-3 img"));
http://jsfiddle.net/czUnU/1/

Categories

Resources