Using setTimeout to display one image at a time - javascript

I'm using a hover function with a fade in and fade out to show and hide images. The problem is I want each image to finish fading before the other begins to fade in.
This is what I'm trying. The setTimeout function has broke the hover function and all images are displaying when the page loads.
$(document).ready(function() {
var delay = 0;
//Everything below repeats for each image
$("#image_e_natural_minor").hide();
$("#hover_e_natural_minor").hover(
if (delay == 1) {
setTimeout(function() {
function () {
$("#image_e_natural_minor").fadeIn(1000);
}, //mouse over
function () {
$("#image_e_natural_minor").fadeOut(1000);
delay = 0;
} //mouse out
); //hover close
},1000); // delay time
}
else {
$("#hover_e_natural_minor").hover(
function () {
delay = 1;
$("#image_e_natural_minor").fadeIn(1000);
}, //mouse over
function () {
$("#image_e_natural_minor").fadeOut(1000);
delay = 0;
} //mouse out
); //hover close
}
This is what I had before that works but it will display two images at once.
$("#image_e_natural_minor").hide();
$("#hover_e_natural_minor").hover(
function () {
$("#image_e_natural_minor").fadeIn(1000);
}, //mouse over
function () {
$("#image_e_natural_minor").fadeOut(1000);
} //mouse out
); //hover close
$("#image_e_harmonic_minor").hide();
$("#hover_e_harmonic_minor").hover(
function () {
$("#image_e_harmonic_minor").fadeIn(1000);
}, //mouse over
function () {
$("#image_e_harmonic_minor").fadeOut(1000);
} //mouse out
); //hover close
Sorry for the poor syntax. I'm very new to programming.

jQuery functions fadeIn and fadeOut both have a callback param which is triggered when the animation finishes, so you can hook the fadeIn for current image call right when fadeOut finishes.
But: try this on a single image first; once you have it working try to rewrite it in a function you can call on every image. Remember DRY principle: Don't Repeat Yourself.
EDIT:
What I mean is: When hover over image A 'hover detector', the function should first fadeOut the currently visible image B (which you can get using :visible's jQuery selector) and when the fadeOut animation finishes it will call the fadeIn of image A (which you provided throw the callback param):
$("#image_e_natural_minor").hide();
$("#hover_e_natural_minor").hover(
function () {
$(".myImageClass:visible").fadeOut(1000, function(){$("#image_e_natural_minor").fadeIn(1000)});
}, //mouse over
function () {
$("#image_e_natural_minor").fadeOut(1000);
} //mouse out
); //hover close
Again: try this with a single image, and then rewrite it so it looks like:
$("#image_e_natural_minor").hide();
$("#hover_e_natural_minor").hover(
function(){showThis('#image_e_natural_minor')}, //mouse over
function(){hideThis('#image_e_natural_minor')} //mouse out
); //hover close

I think what you need is something like this. (In this example you also need to set the hover images to have class='hoverI'.)
var delayF = false,
mouseOn = null;
function setHandlers() {
$(".hoverI").hover(function() {
mouseOn = $('#' + event.target.id.replace('hover_e', 'image_e'));
if (!delayF) {
mouseOn.fadeIn(1000);
mouseOn = null;
}
}, function() {
var image = $('#' + event.target.id.replace('hover_e', 'image_e'));
if (mouseOn == image) mouseOn = null;
delayF = true;
image.fadeOut(1000, function() {
delayF = false;
if (mouseOn) {
mouseOn.fadeIn(1000);
mouseOn = null;
}
});
});
}
$("#image_e_natural_minor").hide();
$("#image_e_harmonic_minor").hide();
setHandlers();​

Related

fade in fade out and stop on mouse hover

I m working on small animation where the link will have fadein fadeout effect with some delay but when when user moveover his mouse on link it should stop and start animate once again once mouse out.
Currently When user moveover mouse on link 2 or more link start appering and its stop at last.
https://jsfiddle.net/e1fye4uy/3/
function InOut(elem) {
elem.delay()
.fadeIn(1000)
.delay(10000)
.fadeOut(1000,
function () {
if (elem.next().length > 0) {
InOut(elem.next());
} else {
InOut(elem.siblings(':first'));
}
}).mouseover(function () {
//$(this).stop(true, false);
// $(this).clearQueue();
elem.stop($(".newsFlash").children('li'), true, false);
}).mouseout(function () {
if (elem.next().length > 0) {
elem.clearQueue();
// elem.finish();
InOut($(this));
}
});};$(function () {
$('#content li').hide();
InOut($('#content li:first'));
});
This is my solution
https://jsfiddle.net/e1fye4uy/8/
var doAniamtion = false;
var lis = $("#content li");
var time;
function start(){
time = setInterval(function(){
next();
}, 2000);
console.log("start" + time);
}
function stop(){
console.log("stop " + time)
clearInterval(time);
}
function next(){
var lisLength = $(lis).length;
for(var i=0;i<lisLength;i++)
if($(lis[i]).hasClass("current"))
{
fadOut(lis[i],function(){
fadIn(((i+1) < lisLength) ? lis[i+1] : lis[0]);
});
return;
}
}
function fadIn(obj, callback){
$(obj).addClass("current");
$(obj).animate({
opacity:1
},500,function(){
callback && callback();
});
}
function fadOut(obj, callback){
$(obj).addClass("current");
$(obj).animate({
opacity:0
},500,function(){
$(obj).removeClass("current");
callback && callback();
});
}
start();
$("#content").mouseover(function(){
stop();
});
$("#content").mouseout(function(){
start();
});
So, I decide to use animation instead of use fadeIn and fadeOut, setInterval (+info http://www.w3schools.com/jsref/met_win_setinterval.asp) and class "current" in the li HTML element to know witch li is current visible.
PS:
For change the time that li remains visible change the setInterval Time.
For make the animations more fast or slow change the time in animation inside of fadIn and fadout functions
Any doubt about the code, ask!

Navbar Irregularly Appearing and Disapearing

I have a code that is intended to make a navbar disappear when the mouse is still, and when the mouse moves, it is supposed to fade in. The code works, except that when the mouse is still, the navbar will fade out, but then will fade in a couple seconds later, and continue fading out and in at regular intervals. The website with the problem is here.
My code is below
$("#header").hide();
$("html").mousemove(function( event ) {
$("#header").fadeIn(1500);
myStopFunction();
myFunction();
});
function myFunction() {
myVar = setTimeout(function(){
$("#header").fadeOut(1500);
}, 2000);
}
function myStopFunction() {
if(typeof myVar != 'undefined'){
clearTimeout(myVar);
}
}
Try this (pattern)
$(function () {
var _toggle = function () {
$(document).one("mousemove.t", function (e) {
e.target = $("#header");
$(e.target).toggle(1500).delay(2000).toggle(1500, function () {
_toggle()
})
})
};
$.when(_toggle())
})
jsfiddle http://jsfiddle.net/guest271314/8VeDN/

How to pause slideshow when hovering

How do I add a pause effect when I hover over an image in a jQuery slideshow?
$(document).ready(function () {
slideShow();
});
function slideShow() {
var showing = $('#slideshow .show');
var next = showing.next().length ? showing.next() : showing.parent().children(':first');
var timer;
showing.fadeOut(500, function () {
next.fadeIn(200).addClass('show');
}).removeClass('show');
setTimeout(slideShow, 3000);
}
var hovering = false; //default is not hovering
$("#slideshow").hover(function () { //*replace body with your element
hovering = true; //when hovered, hovering is true
}, function () {
hovering = false; //when un-hovered, hovering is false
slideShow(); //start the process again
});
function slideShow() {
if(!hovering) { //if not hovering, proceed
/* Your code here*/
nextSlide();
setTimeout(slideShow, 1000);
}
}
function nextSlide(){
var showing = $('#slideshow .show');
var next = showing.next().length ? showing.next() : showing.parent().children(':first');
var timer;
showing.fadeOut(500, function () {
next.fadeIn(200).addClass('show');
}).removeClass('show');
}
Demo: http://jsfiddle.net/DerekL/mqEbZ/
Use .delay() that will help.
Description: Set a timer to delay execution of subsequent items in the queue.
I think you need two functions for that ... slideShow() and other one say pauseSlideshow()... now call the slideshow() on mouseout event and on mouseenter call pauseSlideShow()
your code should be something like this
$(document).ready(function(){
$('.slider').mouseout( slideShow());
$('.slider').mouseenter( pauseSlideShow());
});
function slideShow() {
var showing = $('#slideshow .show');
var next = showing.next().length ? showing.next() : showing.parent().children(':first');
var timer;
showing.fadeOut(500, function() { next.fadeIn(200).addClass('show'); }).removeClass('show');
timeOut = setTimeout(slideShow, 3000);
}
function PauseSlideShow() {
window.clearTimeout(timeOut);
}
TRY IT
Working off of Derek's answer, an alternative to hover would be to use mouseenter and mouseleave.
See the working slideshow Jsfiddle: Demo: http://jsfiddle.net/highwayoflife/6kDG7/
var hovering = false;
var slideshow = $("#slideshow");
slideshow.mouseenter(function() {
hovering = true;
}).mouseleave(function() {
hovering = false;
slideShow();
});
function slideShow() {
if (!hovering) {
# Some browsers don't interpret "display:block" as being visible
# If no images are deemed visible, choose the first...
var currentImg = (slideshow.children("img:visible").length) ? slideshow.children("img:visible") : slideshow.children("img:first");
var nextImg = (currentImg.next().length) ? currentImg.next() : slideshow.children("img:first");
currentImg.fadeOut(500, function() {
nextImg.fadeIn(500, function() {
setTimeout(slideShow, 2000);
});
});
}
}
$(document).ready(function() {
slideShow();
});

does jQuery stop() work on custom functions?

There are three images that I have made a tooltip for each.
I wanted to show tooltips within timed intervals say for 2 seconds first tooltip shows and for the second interval the 2nd tooltips fades in and so on.
for example it can be done with this function
function cycle(id) {
var nextId = (id == "block1") ? "block2": "block1";
$("#" + id)
.delay(shortIntervalTime)
.fadeIn(500)
.delay(longIntervalTime)
.fadeOut(500, function() {cycle(nextId)});
}
now what i want is to stop the cycle function when moseover action occurs on each of the images and show the corresponding tooltip. And again when the mouse went away again the cycle function fires.
If I understand everthing correctly, than try this code. Tt stops the proccess if you hover the image and continues if you leave the image. The stop() function will work on custom functions if you implement them like the fadeOut(), slideIn(), ... functions of jquery.
$('#' + id)
.fadeIn(500, function () {
var img = $(this).find('img'),
self = $(this),
fadeOut = true;
img.hover(function () {
fadeOut = false;
},
function () {
window.setTimeout(function () {
self.fadeOut(500);
}, 2000);
}
);
window.setTimeout(function () {
if (fadeOut === false) {
return;
}
self.fadeOut(500);
}, 2000);
});​

Javascript "while hovered" loop

Can anybody help me on this one...I have a button which when is hovered, triggers an action. But I'd like it to repeat it for as long as the button is hovered.
I'd appreciate any solution, be it in jquery or pure javascript - here is how my code looks at this moment (in jquery):
var scrollingposition = 0;
$('#button').hover(function(){
++scrollingposition;
$('#object').css("right", scrollingposition);
});
Now how can i put this into some kind of while loop, so that #object is moving px by px for as #button is hovered, not just when the mouse enters it?
OK... another stab at the answer:
$('myselector').each(function () {
var hovered = false;
var loop = window.setInterval(function () {
if (hovered) {
// ...
}
}, 250);
$(this).hover(
function () {
hovered = true;
},
function () {
hovered = false;
}
);
});
The 250 means the task repeats every quarter of a second. You can decrease this number to make it faster or increase it to make it slower.
Nathan's answer is a good start, but you should also use window.clearInterval when the mouse leaves the element (mouseleave event) to cancel the repeated action which was set up using setInterval(), because this way the "loop" is running only when the mouse pointer enters the element (mouseover event).
Here is a sample code:
function doSomethingRepeatedly(){
// do this repeatedly when hovering the element
}
var intervalId;
$(document).ready(function () {
$('#myelement').hover(function () {
var intervalDelay = 10;
// call doSomethingRepeatedly() function repeatedly with 10ms delay between the function calls
intervalId = setInterval(doSomethingRepeatedly, intervalDelay);
}, function () {
// cancel calling doSomethingRepeatedly() function repeatedly
clearInterval(intervalId);
});
});
I created a sample code on jsFiddle which demonstrates how to scroll the background-image of an element left-to-right and then backwards on hover with the code shown above:
http://jsfiddle.net/Sk8erPeter/HLT3J/15/
If its an animation you can "stop" an animation half way through. So it looks like you're moving something to the left so you could do:
var maxScroll = 9999;
$('#button').hover(
function(){ $('#object').animate({ "right":maxScroll+"px" }, 10000); },
function(){ $('#object').stop(); } );
var buttonHovered = false;
$('#button').hover(function () {
buttonHovered = true;
while (buttonHovered) {
...
}
},
function () {
buttonHovered = false;
});
If you want to do this for multiple objects, it might be better to make it a bit more object oriented than a global variable though.
Edit:
Think the best way of dealing with multiple objects is to put it in an .each() block:
$('myselector').each(function () {
var hovered = false;
$(this).hover(function () {
hovered = true;
while (hovered) {
...
}
},
function () {
hovered = false;
});
});
Edit2:
Or you could do it by adding a class:
$('selector').hover(function () {
$(this).addClass('hovered');
while ($(this).hasClass('hovered')) {
...
}
}, function () {
$(this).removeClass('hovered');
});
var scrollingposition = 0;
$('#button').hover(function(){
var $this = $(this);
var $obj = $("#object");
while ( $this.is(":hover") ) {
scrollingposition += 1;
$obj.css("right", scrollingposition);
}
});

Categories