Trigger if continously hover for certain time [duplicate] - javascript

This question already has answers here:
setTimeout / clearTimeout problems
(8 answers)
Closed 9 years ago.
I need to trigger a method when a hover is made on a button for continous 1000 ms. Whenever hover is on other elements then timeout should be reset. How do I implement such thing using javascript/ jquery ?
Preferred solution would be one not requiring use of new plugin.

Try
$(function(){
var timer;
$('.item').hover(function(){
timer = setTimeout(function(){
console.log('do it')
}, 1000);
}, function(){
clearTimeout(timer);
});
})
Update:
$(function(){
$('body').on('mouseenter', '.item', function(e){
var timer = setTimeout(function(){
console.log('do it', e.target)
}, 1000);
$(this).data('myTimer', timer);
}).on('mouseleave', '.item', function(e){
clearTimeout($(this).data('myTimer'));
});
})
Demo: Fiddle

Related

Chaining methods in jquery [duplicate]

This question already has answers here:
Jquery delay execution of script
(2 answers)
Closed 4 years ago.
I'm trying to make an animation by adding a class pressed then wait for 100ms then remove the class.
when I just add the class
$("#" + currentColor).addClass("pressed");
the code works fine. But when I chain the methods or write them separately none of the methods work.
$(".btn").on("click", function () {
var userChosenColor = $(this).attr("id");
animatePress(userChosenColor);
});
function animatePress(currentColor) {
$("#" +
currentColor).addClass("pressed").delay(100).removeClass("pressed");
}
I expect it to add the class pressed then wait 100ms then remove the classpressed. But it doesn't do anything. I also don't get any error report in the console
That is because the delay method only delays effects, such as fadeIn. It will not delay adding or removing classes. You should use setTimeout for that.
$(".btn").on("click", function () {
var userChosenColor = $(this).attr("id");
animatePress(userChosenColor);
});
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
window.setTimeout(function () {
$("#" + currentColor).removeClass("pressed");
}, 100);
}
You can use setTimeout() method for delaying the second action.
Your code should be like this:
$(".btn").on("click", function () {
var userChosenColor = $(this).attr("id");
animatePress(userChosenColor);
});
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
setTimeout(function(){
$("#" + currentColor).removeClass("pressed")
},100)
}

How can I cancel setTimeout? [duplicate]

This question already has answers here:
Cancel/kill window.setTimeout() before it happens
(2 answers)
Closed 7 years ago.
I wrote this simple Javascript for auto and manually hiding bootstrap alerts.
$(function () {
$.ajaxSetup({ cache: false });
$("[data-hide]").on("click", function () {
$(this).closest("." + $(this).attr("data-hide")).hide();
});
window.setTimeout(function () {
$(".alert").fadeTo(700).slideUp(700, function () {
$(this).hide();
});
}, 5000);
});
I want to cancel the setTimeout when the cancel button is clicked. How can I do this?
setTimeout returns a numeric timeoutId for your timer. You can pass that to the clearTimeout method.
$(function () {
var t = window.setTimeout(function () {
$(".alert").fadeTo(700).slideUp(700, function () {
$(this).hide();
});
}, 5000);
$("#yourHideButtonId").on("click", function () {
if(t!=null)
{
clearTimeout(t);
}
});
});
To start timer:
timer = window.setTimeout( f , 5000);
To clear it:
window.clearTimeout(timer);

Delay jQuery fadeIn due to unwanted behavior

How do I make my .right-menu DIV to fadein only after a couple of moments the mouse is hovering its parent .right-menu-background ? The thing is that when you move the cursor quickly in and out, .right-menu DIV is reappearing a lot of times after.
How do I delay animation for few ms?
Here's the code:
$(function(){
$(".right-menu-background").hover(function(){
$(this).find(".right-menu").fadeIn();
}
,function(){
$(this).find(".right-menu").fadeOut();
}
);
});
a easy fix is to use .stop()
$(function () {
$(".right-menu-background").hover(function () {
$(this).find(".right-menu").stop(true, true).fadeIn();
}, function () {
$(this).find(".right-menu").stop(true, true).fadeOut();
});
});
using timer
$(function () {
$(".right-menu-background").hover(function () {
var el = $(this).find(".right-menu");
var timer = setTimeout(function(){
el.stop(true, true).fadeIn();
}, 500);
el.data('hovertimer', timer);
}, function () {
var el = $(this).find(".right-menu");
clearTimeout(el.data('hovertimer'))
el.stop(true, true).fadeOut();
});
});
Use the stop() function in front of fading calls ...stop(true, true)
With those two parameters set to true, the animation queue is cleared and the last animation is played this will get ride of the weird effect
$(this).find(".right-menu").stop(true, true).fadeIn();
Use .delay() function.
Here is the code:
$(function(){
$(".right-menu-background").hover(function(){
$(this).find(".right-menu").delay(800).fadeIn(400);
},function(){
$(this).find(".right-menu").fadeOut(400);
});
});
Check the demo here: http://jsfiddle.net/Mju7X/

How do I change images every 6 seconds? [duplicate]

This question already has an answer here:
How can I execute javascript code every a specific time interval?
(1 answer)
Closed 9 years ago.
How do I add an interval to the below code so it does it change images automatically every 6 seconds?
I use this code from fearlessflyer.com
$(window).load(function () {
var theImage = $('ul li img');
var theWidth = theImage.width();
//wrap into mother div
$('ul').wrap('<div id="mother" />');
//assign height width and overflow hidden to mother
$('#mother').css({
width: function () {
return theWidth;
},
height: function () {
return theImage.height();
},
position: 'relative',
overflow: 'hidden'
});
//get total of image sizes and set as width for ul
var totalWidth = theImage.length * theWidth;
$('ul').css({
width: function () {
return totalWidth;
}
});
$(theImage).each(function (intIndex) {
$(this).nextAll('a')
.bind("click", function () {
if ($(this).is(".next")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (-(intIndex + 1) * theWidth)
}, 1000)
} else if ($(this).is(".previous")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (-(intIndex - 1) * theWidth)
}, 1000)
} else if ($(this).is(".startover")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (0)
}, 1000)
}
}); //close .bind()
}); //close .each()
}); //doc ready
Here is an extended answer
var intNum = 6000; //repeat every 6 seconds
function startInterval(){
window.int = setInterval(function(){
//code to move to next image
},intNum);
}
That will set the interval for the image, going to the next automatically, small adjustments might be needed when comparing to your click event for the switch, so I left the inside blank.
the function startInterval() should be called when you know that the rest of the code is loaded and ready (click events are set, ect).
When you do a click event to manually switch back and forth you want to use the following
clearInterval(int);
//code to switch image from click
startInterval();
You need to use the setInterval() function.
Basically, it would look something like:
var currentImg=0;//Current image tracker
var imgList["img1.jpg","img2.jpg","img3.jpg"];//Image names
var changeImage = function(){
//Change src attribute on img element
$('ul li img').attr('src','/imgdir/'+imgList[currentImg]);
if(currentImg>=imgList.length-1)//Check if current image is the last in the list
currentImg=0;//Sets to first images if true
else
currentImg++;//Sets to next image if false
}
//Sets an interval of 6000ms on the window object that calls the function changeImage()
//on every trigger
window.setInterval(changeImage(),6000);
MDN Reference
Hope this helps, I'd suggest checking out the jQuery Documentation aswell...
Use the setInterval() javascript function, as explained here.

How to add delay to jquery mouseover? [duplicate]

This question already has answers here:
Delay jquery hover event?
(6 answers)
Closed 7 years ago.
I have a bunch of images on one page and I am using the following to trigger an event:
$('.img').on('mouseover', function() {
//do something
});
Is there some way to add a delay such that if a user hovers for maybe 1 second, then it does "//do something" or actually triggers the "mouseover" event?
You can use setTimeout
var delay=1000, setTimeoutConst;
$('.img').on('hover', function() {
setTimeoutConst = setTimeout(function() {
// do something
}, delay);
}, function() {
clearTimeout(setTimeoutConst);
});
You could do that using a setTimeout along with a clearTimeout if the user leaves too soon:
var timer;
var delay = 1000;
$('#element').hover(function() {
// on mouse in, start a timeout
timer = setTimeout(function() {
// do your stuff here
}, delay);
}, function() {
// on mouse out, cancel the timer
clearTimeout(timer);
});
Use a timer and clear it when they mouseout incase they leave within 1000ms
var timer;
$('.img').on({
'mouseover': function () {
timer = setTimeout(function () {
// do stuff
}, 1000);
},
'mouseout' : function () {
clearTimeout(timer);
}
});
I was looking for something like this as well, but with a secondary delay as well. I took one of the answers here and expanded upon it
This example shows a div after X seconds of mouseover and hides it after X seconds of mouseout. But disables if you hover over the shown div.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
.foo{
position:absolute; display:none; padding:30px;
border:1px solid black; background-color:white;
}
</style>
<h3 class="hello">
<a href="#">Hello, hover over me
<span class="foo">foo text</span>
</a>
</h3>
<script type="text/javascript">
var delay = 1500, setTimeoutConst,
delay2 = 500, setTimeoutConst2;
$(".hello").mouseover(function(){
setTimeoutConst = setTimeout(function(){
$('.foo').show();
},delay);
}).mouseout(function(){
clearTimeout(setTimeoutConst );
setTimeoutConst2 = setTimeout(function(){
var isHover = $('.hello').is(":hover");
if(isHover !== true){
$('.foo').hide();
}
},delay2);
});
</script>
Working example
You can use jquery .Delay like this (not tested):
$("#test").hover(
function() {
$(this).delay(800).fadeIn();
}
);
http://api.jquery.com/delay/

Categories

Resources