Stop loop and fade in area that is hovered on - javascript

I have a bit of javascript/jquery I am trying to figure out. What I have already is three boxes that the content fades in and out and loops through the three and repeats. What I am trying to do is when "box x" is hovered over the loop fades out and stops never to start again, and the box that is hovered on, the content below the box fades in and stays... unless another box is hovered over, then the content that faded in from the other hovered box will fade out and the new box that was hovered on, the content that coincides with that box fades in and stays fade in, and so forth.
How would I go about doing this?
Here is a jsfiddle example: http://jsfiddle.net/q0htx0no/
javascript/jquery
var infoboxes = $(".count p");
var counter = 0;
function rotate() {
$(infoboxes[counter]).fadeIn(1000, function() {
setTimeout(function() {
$(infoboxes[counter]).fadeOut(1000, function() {
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
rotate();
})
}, 1000);
});
}
$(function() {
rotate();
});
Thanks for any help

One option would be to have a global variable (a 'flag') that would indicate if the rotation should be stopped. Once a box has been hovered over, it should set hovered to True and should fade in that specific box.

Yep, use a global variable. Something like this:
var infoboxes = $(".count p");
var counter = 0;
var goAhead = true;
function rotate() {
$(infoboxes[counter]).fadeIn(1000, function() {
setTimeout(function() {
$(infoboxes[counter]).fadeOut(1000, function() {
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
checkRotate();
})
}, 1000);
});
}
function checkRotate() {
if (goAhead) { rotate(); }
}
$('.about').on('mouseover', function() {
goAhead = false;
var index = $(this).index();
var boxesToClear = $(infoboxes).filter(function(i) { return i !== index; });
$(boxesToClear).fadeOut(1000, function() {
$(infoboxes[index]).fadeIn(1000);
});
});
checkRotate();
DEMO

Here's one way to do it. It can probably be improved.
http://jsfiddle.net/vbt67x0h/2/
var infoboxes = $(".count p");
var counter = 0;
var isrotating = false;
function rotate(){
isrotating = true;
$(infoboxes[counter]).fadeIn(1000).delay(1000).fadeOut(1000);
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
}
//immediately stop rotate and hide all
function stoprotate(){
clearInterval(tmrrotate);
isrotating = false;
for(var x=0;x<infoboxes.length;x++){
$(infoboxes[x]).stop();
$(infoboxes[x]).hide();
}
}
rotate();
//rotate every 3 seconds, 1 to fadein, 1 to pause, 1 to fadeout
var tmrrotate = setInterval(function() {
rotate();
}, 3000);
$(".about").on('mouseover', function() {
if(isrotating){stoprotate()}
$(infoboxes[$(this).index()]).fadeIn(1000);
})
.on('mouseleave', function() {
$(infoboxes[$(this).index()]).fadeOut(1000);
});

You should make a timed array:
var arTimer = [];
and push all timers into that array, clearTimeout on hover and show only hovered index:
var infoboxes = $(".count p");
var counter = 0;
var arTimer = [];
function rotate() {
$(infoboxes[counter]).fadeIn(1000, function() {
arTimer.push(setTimeout(function() {
$(infoboxes[counter]).fadeOut(1000, function() {
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
rotate();
})
}, 1000));
});
}
function cleararTimer(){
for (var i = 0; i < arTimer.length; i++) {
clearTimeout(arTimer[i]);
}
}
$(function() {
rotate();
$('.about').on('mouseover', function(){
cleararTimer();
var hovered = $(this).index();
$('.count p').not(':eq('+hovered+')').fadeOut(1000);
$('.count p:eq('+hovered+')').fadeIn(1000);
});
});
jsFiddle Example

Related

Converting a manual slideshow to automatic

I followed a tutorial and created a simple manual loop slideshow. I'm trying to make it so it changes the slide automatically even if the prev/next buttons aren't clicked. I tried a crude approach by setting a delay between automatic click events on the "next" button but for some reason it clicks it only once and stops. My js knowledge is very limited and can't figure it out, any input is appreciated. This is the script so far:
$(function() {
var ul = $(".slider ul");
var slide_count = ul.children().length;
var slide_width_pc = 100.0 / slide_count;
var slide_index = 0;
var first_slide = ul.find("li:first-child");
var last_slide = ul.find("li:last-child");
last_slide.clone().prependTo(ul);
first_slide.clone().appendTo(ul);
ul.find("li").each(function(indx) {
var left_percent = (slide_width_pc * indx) + "%";
$(this).css({"left":left_percent});
$(this).css({width:(100 / slide_count) + "%"});
});
ul.css("margin-left", "-100%");
$(".slider .prev").click(function() {
console.log("prev button clicked");
slide(slide_index - 1);
});
$(".slider .next").click(function() {
console.log("next button clicked");
slide(slide_index + 1);
});
function slide(new_slide_index) {
var margin_left_pc = (new_slide_index * (-100) - 100) + "%";
ul.animate({"margin-left": margin_left_pc}, 400, function() {
if(new_slide_index < 0) {
ul.css("margin-left", ((slide_count) * (-100)) + "%");
new_slide_index = slide_count - 1;
}
else if(new_slide_index >= slide_count) {
ul.css("margin-left", "-100%");
new_slide_index = 0;
}
slide_index = new_slide_index
});
}
});
Here is an approach to make it sliding automatically...
But if user clicks on prev/next, it holds the automatic feature for a defined "idle" time.
It need two lines added to your click handlers:
var autoEnabled = true; // ADDED
$(".slider .prev").click(function() {
console.log("prev button clicked");
slide(slide_index - 1);
autoEnabled = false; // ADDED
disabledCount = 0; // ADDED
});
$(".slider .next").click(function() {
console.log("next button clicked");
slide(slide_index + 1);
autoEnabled = false; // ADDED
disabledCount = 0; // ADDED
});
And this to cyclically slide or check if it can re-enable itself.
// ----------------- Automatic sliding interval with "idle time" to re-enable on user click
var idleTime = 5000; // Time without manual click to re-enable automatic sliding.
var autoSlideDelay = 1000; // Time between each slide when automatic.
var disabledCount = 0;
var autoSlide = setInterval(function(){
if(autoEnabled || disabledCount >= idleTime/autoSlideDelay ){
disabledCount = 0;
autoEnabled = true;
slide(slide_index + 1);
}else{
disabledCount++;
}
},autoSlideDelay);
var break_auto_slide = false;
function auto_silde()
{
if(break_auto_slide)
{
break_auto_slide = false;
return;
}
slide(slide_index + 1);
setTimeout(auto_silde,1000 /* time in ms*/);
}
setTimeout will call the function in a specified timeout in milliseconds.
Variable break_auto_slide - set it to true to stop the automatic slide. Next time the function is called it will return without setting a new timer and will reset this variable so auto mode can be turned on again.

Previous and Next functions for js slider

I have almost finished this slider, but I don't know how to implement the functionality for next() and prev(). How can I implement these functions?
http://jsfiddle.net/M4t4L/11/
$(function () {
var container = $("#scene"),
i = 0,
count = container.find("li").length,
j = container.find("li").length - 1,
isAnimating = false;
container.find("li:first").css({
"width": "100%"
});
$("#trigger").click(function (e) {
if (!isAnimating) {
isAnimating = true;
e.preventDefault(e);
i++; if (i >= count) { i = 0; }
j++; if (j >= count) { j = 0; }
container.find("li")
.finish()
.removeClass('active')
.last()
.width(0)
.addClass("active")
.animate({
"width": "100%"
}, 800,
function () {
container.find("li").first().appendTo(container);
isAnimating = false;
});
}
});
});
The problem is that when I implement these functions and press the next or prev. Displays the last slide on one second, and then switches to the desired
http://jsfiddle.net/M4t4L/9
If you want to get a Next or Prev function running, you want to take control of the number of the slider where you are. I'm afraid you will have to play around with your i/j and make the position go in both directions.
Right now you count up your i and j, where you might want to go is to have a position var and an array of slider objects, then the click only would have to call for the next/prev object to be loaded and the animation can begin.
Something like this maybe..
var pos = 0;
var container = $('#scene').find('li');
$('.back').click(function() {
pos = pos - 1;
moveIt(pos);
});
$('.forth').click(function() {
pos = pos +1;
moveIt(pos);
});
function moveIt(pos) {
container[pos]... // Your animation goes here
}

Adding delay to DIV animation

I'm trying to create div boxes step by step and animate them for several times when a button is pressed. I have a running code, and everything is going well. It goes right to the endhost, then it goes left again to its original place. This is mainly what I do, and also the demo is found here: http://jsfiddle.net/54hqm/3/
Now I want to happen after each click, is basically to move each DIV one after another, with a delay, instead of moving the whole stack of DIVs at once. I don't exactly know what to do. Can anyone help me with that?
$(document).ready(function () {
var count = 0;
var items = 0;
var packetNumber = 0;
var speed = 0;
$("button").click(function () {
if (count < 4) {
items = items + 1;
count++;
} else {
items = items * 2;
}
speed = $("#speed").val();
createDivs(items);
animateDivs();
});
function createDivs(divs) {
packetNumber = 1;
var left = 60;
for (var i = 0; i < divs; i++) {
var div = $("<div class='t'></div>");
div.appendTo(".packets");
$("<font class='span'>" + packetNumber + "</font>").appendTo(div);
packetNumber++;
div.css("left",left+"px");
div.hide();
left += 20;
}
}
function animateDivs() {
$(".t").each(function () {
var packet = $(this);
packet.show();
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
top: '+=20px',
backgroundColor: "#f09090",
text: '12'
}, speed / 4, "swing", function () {
$('.span').fadeOut(100, function () {
$(this).text(function () {
return 'a' + $(this).text().replace('a', '');
}).fadeIn(100);
});
});
packet.delay(1000).animate({left:'-=230px'}, speed);
packet.animate({left:'-=230px'}, speed);
}).promise().done(function(){
$(".packets").empty();});
}
});
You can make this with 2 small modifications:
In your each() function, add the index parameter to know the index of the currently animating packet:
$(".t").each(function (index) {
Before your animate calls, insert a packet.delay() with a delay increasing with every item:
packet.delay(index * 250);
I updated your fiddle to show results.
Update: I made a second version based on your comment.

my jquery slider is running well but there is bug that it sometimes does'nt shows images on next or prev click

Found solution for the playing and stopping the slider.But problem is now with my next and prev links .these links some times does not shows any image.
my code is on the
http://jsfiddle.net/yogesh84/ftkLd/12/
var slides;
var cnt;
var amount;
var i;
var x;
var timer;
slides = jQuery('#my_slider').children();
cnt = jQuery('#counter');
amount = slides.length;
i=amount;
cnt.text(i+' / '+amount);
function run_prev() {
jQuery(slides[i]).fadeOut(1000);
i--;
if (i <= 0) i = amount;
jQuery(slides[i]).fadeIn(1000);
// updating counter
cnt.text(i+' / '+amount);
}
x=0;
function run_next() {
// hiding previous image and showing next
jQuery(slides[x]).fadeOut(1000);
x++;
if (x >= amount) x = 0;
jQuery(slides[x]).fadeIn(1000);
cnt.text(x+1+' / '+amount);
}
/***********start and stop functions***************/
function run() {
// hiding previous image and showing next
jQuery(slides[x]).fadeOut(1000);
x++;
if (x >= amount) x = 0;
jQuery(slides[x]).fadeIn(1000);
timer = setTimeout(run,2000);
}
function MySlider() {
timer = setTimeout(run,2000);
}
function stoper() {
clearTimeout(timer);
}
/***********end start and stop functions***************/
function slide_show(){
var timer;
if(jQuery('#slide_show').html()=='Play Slideshow')
{
jQuery('#slide_show').html('Stop Slideshow');
MySlider();
}
else
{
jQuery('#slide_show').html('Play Slideshow');
stoper()
}
}
// custom initialization
jQuery('#prev2').on("click",run_prev);
jQuery('#next2').on("click",run_next);
jQuery('#slide_show').on("click",slide_show);
I think you forgot to set timer
You declare at the top: timer but it is never filled.
So i think you should do:
timer = setTimeout( run, inetrval );
Also take the function outside of Run()
function run() {
}
if ( inetrval > 0 ) {
alert( inetrval );
run();
timer = SetTimeOut( run, inetrval )
}

Looping code when hovering with set delay in JavaScript with jQuery

I'm looking to start and stop a loop with a set delay with a jQuery hover event. I've been trying to do it with "mouseover" and "mouseout" with no luck.
Example (odd psudocode):
Mouseover
Loop
Change text colour
Wait 100ms
Mouseout
Stop loop
I'm sure this is super easy, I just don't quite know how to structure it with JavaScript.
Thanks in advance.
This might work:
$(function(){
$('#test').hover(function(){
var self = $(this),
rnd = null,
col = null;
this.iid = setInterval(function(){
col = ['#'];
rnd = ~~(Math.random()*255);
col.push(rnd.toString(16).length < 2 ? '0' + rnd.toString(16) : rnd.toString(16));
col.push(rnd.toString(16).length < 2 ? '0' + rnd.toString(16) : rnd.toString(16));
col.push(rnd.toString(16).length < 2 ? '0' + rnd.toString(16) : rnd.toString(16));
self.css({backgroundColor: col.join('')});
}, 100);
}, function(){
if(this.iid){
clearInterval(this.iid);
delete this.iid;
}
});
});​
See this in action: http://www.jsfiddle.net/YjC6y/19/
function rgb() {
var color = 'rgb(';
for (var i = 0; i < 3; i++) {
color += Math.floor(Math.random() * 255) + ',';
}
return color.replace(/\,$/, ')')
}
var loop = null;
$(function () {
$('#someid').hover(function () {
var $this = $(this);
loop = setInterval(function () {
$this.css({backgroundColor: rgb() });
}, 100);
}, function () {
clearInterval(loop);
});
});
try an example : http://jsbin.com/uraxe4
$("#yourElem").hover(
function () { /* mousenter */
$this = $(this);
// take note that the mouse is currently hovering
$this.data("isHovering", true);
// create an interval and store its ID in jQuery data
$this.data("loopId", setInterval(function () {
// only do something if we are still hovering
if ($this.data("isHovering")) {
$this.css("color", getRandomColorValue());
}
}, 100);
},
function () { /* mouseleave */
$this = $(this);
// take note that the mouse is no longer hovering
$this.data("isHovering", false);
// clear the interval that was set and delete the ID
if ($this.data("loopId")) {
clearInterval($this.data("loopId"));
$this.data("loopId", false);
}
}
)
changeColorTimerId = -1;
$('.box').hover(function(){
//mouseOver code here
changeColorTimerId = setInterval ( changeColor, 1000 );
},function(){
//mouseOut code here
if ( changeColorTimerId ){
clearInterval ( changeColorTimerId )
}
});
function changeColor(){
$(".box").css ( 'backgroundColor', '' + getRandomColor() );
}
function getRandomColor(){
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
working example here:
http://jsbin.com/etogi3/2

Categories