Combining actions on event handlers in jQuery [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Below is a jQuery statement which hides a div element on it's click event. I'd like the element to fade out regardless if it isn't clicked after 5 seconds. Is there a simple way I can call the fadeOut function in the same expression or without the click event interfering with the animation?
$(".fadeOutbox").click(function(){
$(this).fadeOut('slow');
});

Most jQuery components are chain-able, your function as it stands returns a reference to the initial object.
You can achieve what you want simply by using:
$(".fadeOutbox").click(function () {
$(this).stop().fadeOut('slow');
}).delay(5000).fadeOut('slow');
Basically reads as onclick, fade out otherwise fade out after 5 seconds.

I assume this is inside another function that shows the box to begin with. This solution will hide the box after 5 seconds, or immediately upon clicking.
var $box = $('.fadeOutbox');
var fadeOut = function() {
clearTimeout(timeout);
$box.fadeOut('slow');
};
var timeout = setTimeout(fadeOut, 5000);
$box.click(fadeOut);

Save the fact that the user has clicked or not and test it in the timer
var isClicked = false;
setTimeout(function () {
if(!isClicked)
$(".fadeOutbox").fadeOut('slow');
}, 5000);
$(".fadeOutbox").click(function () {
isClicked = true;
});

Try this:
var wasClicked = false;
$(".fadeOutbox").click(function () { wasClicked = true; });
setTimeout(function () {
if(wasClicked = false)
$(".fadeOutbox").fadeOut('slow');
}, 5000);

Use a timeout not inside of the click handler:
setTimeout(function () {
$(".fadeOutbox").fadeOut('slow');
}, 5000);
Your jQuery code becomes:
// set a timeout for 5 seconds
setTimeout(function () {
$(".fadeOutbox").fadeOut('slow');
}, 5000);
// attach click handler
$(".fadeOutbox").on("click", function () {
$(this).fadeOut('slow');
});
JSFIDDLE

Edit to clarify:
var clear = setTimeout(function(){ $(".fadeOutbox").fadeOut('slow'); }, 5000);
$(".fadeOutbox").on('click', function(){
clearTimeout(clear);
});
Demo: http://jsfiddle.net/mGbHq/

Try holding a variable for the timeout and clear it every time the user clicks.
Working example
// Timeout variable
var t;
$('.fadeOutBox').click(function()
{
$box = $(this);
$box.fadeIn("fast");
// Reset the timeout
clearTimeout(t);
t = setTimeout(function()
{
$box.fadeOut("slow");
}, 5000);
});
Hope this helps you.

Wow, none of the answers gives the simple solution: Use setTimeout and cancel the timeout on click:
$(".fadeOutbox").click(function () {
// Cache the jQuery object
var $this = $(this);
// Do we already have a timer running?
var timer = $this.data("timer");
if (timer) {
// Yes, cancel it
clearTimeout(timer);
$this.removeData("timer");
}
// (You may want an `else` here, it's not clear)
// In five seconds, fade out
$this.data("timer", setTimeout(function() {
$this.removeData("timer");
$this.fadeOut('slow');
}, 5000));
});
I'm not 100% sure that the above is triggering on the events you want, but the two pieces of relevant code are this, which schedules the timed action:
// In five seconds, fade out
$this.data("timer", setTimeout(function() {
$this.removeData("timer");
$this.fadeOut('slow');
}, 5000));
and this, which cancels it (for instance, on click):
var timer = $this.data("timer");
if (timer) {
// Yes, cancel it
clearTimeout(timer);
$this.removeData("timer");
}

Try
$('#div').delay(5000).fadeOut(400)
Demo

Related

Javascript clearInterval with button click

I'm having issues getting clearInterval to work when I try to bind it to a button click. Also, apparently the function is starting on it's own... Here's my code
var funky = setInterval(function() {
alert('hello world');
}, 2000);
$('#start').click(function() {
funky();
});
$('#stop').click(function() {
clearInterval(funky);
});
Here's a js fiddle
You have forgot to add jquery library and have made wrong assignment, it needs to be inside callback function.
Working example:
var funky;
$('#start').click(function() {
funky = setInterval(function() {
alert('hello world');
}, 2000);
});
$('#stop').click(function() {
clearInterval(funky);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">start</button>
<button id="stop">stop</button>
First off, yes, when you assign a variable to a function, it self invokes.
Secondly, your click events are not working because you need assign the interval to the variable on the click, not invoke the function - there is no function to invoke, as you would see if you looked at your developer console.
Lastly, it is good practice to wrap the jQuery code in the document ready function to ensure all of your event handlers get bound properly.
$(function () {
var funky;
$('#start').click(function() {
funky = setInterval(function() {
alert('hello world');
}, 1000);
});
$('#stop').click(function() {
clearInterval(funky);
});
});
You're saving the wrong value. Try this:
var funky = function() {
alert('hello world');
}
var funkyId = setInterval(funky, 2000);
$('#start').click(function() {
funky();
});
$('#stop').click(function() {
clearInterval(funkyId);
});
Here I am giving you the idea.
declare a variable e.g. let x;
create a function which you want to bind with setInterval.
e.g.
function funky() {
alert("Hello World");
}
assign start.onclick to a function which will assign the setInterval to x.
e.g start.onclick = function(){
clearInterval(x); // to prevent multiple interval if you click more than one
x = setInterval(funky, 2000); // assign the setInterval to x
};
assign stop.onclick to clearInterval(x) to stop the interval.
e.g. stop.onclick = function() {
clearInterval(x); // to stop the interval
};
That's it. Easy right.

How to stop toggling classes [duplicate]

This question already has answers here:
Stop setInterval call in JavaScript
(7 answers)
Closed 7 years ago.
This is how I started toggling classes:
$(document).ready(function() {
window.setInterval(function() {
$('.blinkClass').toggleClass('blink');
}, 500);
});
How can I stop toggling these classes?
You need to store the timer returned from setInterval to a variable which you can then use in a call to clearInterval():
var timer = window.setInterval(function() {
$('.blinkClass').toggleClass('blink');
}, 500);
// later on, in a code block within scope of the above variable...
clearInterval(timer);
You can do this :
$(document).ready(function() {
var myVar = window.setInterval(function() {
$('.blinkClass').toggleClass('blink');
}, 500);
//when you want
myStopFunction(myVar)
});
function myStopFunction(par) {
clearInterval(par);
}
See more info at
setInterval
clearinterval

JQuery Hover Function Timeout

I've seen other similar questions to this on SO but the answers weren't quite what I'm looking for. My problem with the code below is about the variable hide.
In it's current form hide won't be visible to the first hover function, but I don't want to declare it at a higher scope because it has no use there. Plus declaring it at a higher scope would require making a different variable for every li.
What's the solution for keeping this variable containing a timeout between these two functions?
$('li').hover(function() {
clearTimeout(hide);
$('.menu', this).show();
}, function() {
var menu = $('.menu', this);
var hide = setTimeout(function() {
menu.hide();
}, 500);
});
You can store the value with .data()
$('li').hover(function() {
clearTimeout($(this).data('hide'));
$('.menu', this).show();
}, function() {
var menu = $('.menu', this);
$(this).data('hide', setTimeout(function() {
menu.hide();
}, 500));
});

Timer Reset Function Not Working!

Hello Guys!
I have been trying to create a simple sample code for my newest jQuery Plugin, but it doesn't seems to be working at all! Can anyone tell where I'm going wrong?, or can anyone provide me a new function to do it. So my problem is that when I mouse over an element classed trigger an another element classed eg should fadeIn(); but if the user takes out the mouse before the element classed eg fades in it should not be fading in anymore, but this is not working at all. I don't not what is getting wrong? Please help me out. (Below is my Problem HTML nad Jquery Code!)
HTML CODE
<div class="trigger">MouseOverMe</div>
<div class="eg">See Me!</div>
JQUERY CODE
function timereset(a)
{
var elem = $('.'+a);
if(elem.data('delay')) { clearTimeout(elem.data('delay')); }
}
$(document).ready(function () {
$('div.eg').hide();
$('div.trigger').mouseover(function () {
$('div.eg').delay(1000).fadeIn();
});
$('div.trigger').mouseout(function () {
timereset('eg');
$('div.eg').fadeOut();
});
});
THANKS IN ADVANCE
You don't need that timereset stuff, simply call stop() on the object and the previous effect will stop:
http://api.jquery.com/stop/
Update based on the new comment:
$('div.trigger').mouseout(function () {
$('div.eg').stop().hide();
});
jQuery
$('.trigger').hover(function() {
$('.eg').delay(1000).fadeIn();
}, function() {
$('.eg').stop(true, true).hide();
});
Fiddle: http://jsfiddle.net/UJBjg/1
Another option would be to clear the queued functions like:
$('div.trigger').mouseout(function () {
$('div.eg').queue('fx', []);
$('div.eg').fadeOut();
});
Bear in mind if the fadeOut/In has already started by using stop you could end up with a semi-transparent element.
EDIT
Here's an example: http://jsfiddle.net/Qchqc/
var timer = -1;
$(document).ready(function () {
$('div.eg').hide();
$('div.trigger').mouseover(function () {
timer = window.setTimeout("$('div.eg').fadeIn(function() { timer = -1; });",1000);
});
$('div.trigger').mouseout(function () {
if(timer != -1)
window.clearTimeout(timer);
$('div.eg').fadeOut();
});
});

jQuery - link working *only* after some time

I have a link:
Here's my link
This is not a normal clickable link, it's coded in jQuery like this:
$("#link").hover(function(e) {
e.preventDefault();
$("#tv").stop().animate({marginLeft: "50px"});
$("#tv img)").animate({opacity: 1});
})
So after hovering unclickable link there's change of #tv's margin and opacity.
Is there any way of making this work only after the user hovers the link area with pointer for more than two seconds?
Because now everything happens in real time.
I know there's delay(), but it doesn't work because it just delays the animation and in this case I don't want any action if the pointer is over for less than two seconds.
Possible without a loop?
What you're after is called hoverIntent.
var animateTimeout;
$("#link").hover(function() {
if (animateTimeout != null) {
clearTimeout(animateTimeout);
}
animateTimeout = setTimeout(animate, 2000);
}, function() {
clearTimeout(animateTimeout);
});
function animate() {
//do animation
}
You just need a setTimeout() to delay the code, along with a clearTimeout() to clear it if the user leaves the link within 2 seconds.
Example: http://jsfiddle.net/mNWEq/2/
$("#link").hover(function(e) {
e.preventDefault();
$.data(this).timeout = setTimeout(function() {
$("#tv").stop().animate({marginLeft: "50px"});
$("#tv img)").animate({opacity: 1});
}, 2000);
}, function(e) {
clearTimeout($.data(this,'timeout'));
});

Categories