Delay of a few seconds before display:none [duplicate] - javascript

This question already has answers here:
Hide div after a few seconds
(9 answers)
Closed 8 years ago.
I don't know how to achieve that display: none works not immediately.
I need #popUpBox to disappear after a few seconds.
$(document).bind("mousedown", function(){
$('#popUpBox').css({'display':'none'});
jQuery(function($) {
var $txt = '';
$('.selectiontext').bind("mouseup", function(e){
if (window.getSelection){
$txt = window.getSelection();
}
else if (document.getSelection){
$txt = document.getSelection();
}
else if (document.selection){
$txt = document.selection.createRange().text;
}
else return;
if ($txt!=''){
$('#popUpBox').css({'display':'block', 'left':e.pageX+5+'px', 'top':e.pageY+0+'px'});
}
});
$(document).bind("mousedown", function(){
setTimeout(function() {
$('#popUpBox').css({'display':'none'});
}, 2000);
});
Unfortunately, when i select text, now always #popUpBox disappears and i need only when selection is disabled

The following code will hide the div after 2 seconds
$("#popUpBox").delay(2000).hide();
If you want animation, you can use fadeOut method as well
$("#popUpBox").delay(2000).fadeOut('fast');

Try to use the setTimeout function.
$(document).bind("mousedown", function(){
setTimeout(function() {
$('#popUpBox').css({'display':'none'});
}, *time you want(int)*);
});
Edit : To your new question
Add a if statement when selection is disabled. Here :
$(document).bind("mousedown", function(){
*if statement*
setTimeout(function() { (...)
Because it's bound to the entire document, it will always hide the box without any condition.

Try this if you want the function to trigger a few seconds after the mousedown event:
$(document).bind("mousedown", function(){
setTimeout(function() {
$('#popUpBox').css({'display':'none'});
}, 5000);
});
Readup on setTimeout here and here. Basically, setTimeout() allows you to pass a function and then an interval (in milliseconds) to wait before executing that function.
Edit (for update): To only have this happen when there is no selection, try:
$(document).bind("mousedown", function(){
if (!window.getSelection) {
setTimeout(function() {
$('#popUpBox').css({'display':'none'});
}, 5000);
}
});

Related

JQuery .slideUp() after time OR mouseleave

I got an element that is slided down by JQuery using .slideDown() method
$('#dropdown_shopping_cart').slideDown(800);
Now i want it to slide up after 6 seconds, but only if there is no hover on the element, if there is an hover, it should not .slideUp().
So far i worked with a timeout that added display:none to the element while i was giving the element´s hover display:block!important; in CSS so it would not get display: none until the hover is over.
JS
setTimeout(function () {
$('#dropdown_shopping_cart').css('display', 'none');
}, 6000);
_______________________________________________________
CSS
#dropdown_shopping_cart:hover {
display: block!important;
}
Now i want to add the .slideUp() to this.
Check this:
var myVar;
myVar = setTimeout(function() {
$('#dropdown_shopping_cart').slideUp(800)
}, 6000);
$("#dropdown_shopping_cart").hover(
function() {
clearTimeout(myVar);
},
function() {
myVar = setTimeout(function() {
$('#dropdown_shopping_cart').slideUp(800)
}, 6000);
}
);
By default shopping cart will slideUp() after 6 seconds, if mouse hover action occured, setTimeOut will be cleared, after mouse leave the shopping cart, setTimeOut will setted automatically
You can clear the timeout on mouseenter and reset it on mouseleave like this:
var hide_div_to;
function hideDiv(){
hide_div_to = setTimeout(function () {
$('#dropdown_shopping_cart').slideUp(800);
}, 6000);
}
$('#dropdown_shopping_cart').slideDown(800,hideDiv());
$('#dropdown_shopping_cart').mouseenter(function(){
clearTimeout(hide_div_to);
});
$('#dropdown_shopping_cart').mouseleave(function(){
hideDiv();
});
Here is a working JSFiddle
UPDATE
If you don't wan't to wait the timeout again when you leave, after the timeout is reached, you can do this:
$('#dropdown_shopping_cart').slideDown(800);
setTimeout(function () {
if(!$('#dropdown_shopping_cart').is(':hover')){
$('#dropdown_shopping_cart').slideUp(800);
}
else{
$('#dropdown_shopping_cart').mouseleave(function(){
$('#dropdown_shopping_cart').slideUp(800);
});
}
}, 3000);
And here is a JSFiddle and here is another one that shows how this can be triggered multiple times.
Id suggest you work with mouseover and a class:
$('#dropdown_shopping_cart').hover(function(){
if(!$('#dropdown_shopping_cart').hasClass('active'))
{
$(this).addClass('active');
}
else
{
$(this).removeClass('active');
}
},
function() {
var myVar = setTimeout(function() {
if(!$('#dropdown_shopping_cart').hasClass('active'))
{
$('#dropdown_shopping_cart').slideUp()
}
}, 6000);
})
And than in your setTimeout Function you add:
demo: http://jsfiddle.net/yo5gnvy3/7/
$('#dropdown_shopping_cart').hide().slideDown(800, function () {
var events = $._data($(this)[0], "events") || {};
if (events.mouseover === undefined) {
$(this).delay(1000).slideUp()
}
});

preventDefault() on a timer

Does anyone know if there's a way to preventDefault(), but on a timer, so default actions are restored after a certain time?
Here's what I have so far:
function setResetInterval(bool){
var el = $('article');
if(bool){
timer = setInterval(function(){
setTimeout(function(){
console.log('default prevented');
e.preventDefault();
}, 500);
},1000);
}else{
clearInterval(timer);
}
}
if(object.touch.touch){
object.header.menu_button.attr('href',null);
object.touch.articles = $('article');
object.content_blocks.on('click','article',{},function(e){
object.touch.articles.removeClass('on');
$(this).addClass('on');
e.stopPropagation();
setResetInterval(true);
setTimeout(
function() { setResetInterval(false); }, 500);
});
}
Problem is, the function is called after the clickthrough and the action is not prevented. The alternative is the prevent the default action on click, which stop scrolling on mobile devices.
Thinking about it more clearly, the real problem is the click tag in question is basically the entire screen width on mobile.
To build on what Cayce said, one way to approach this is to tie the functionality to a class you later remove.
Demo Fiddle:
In the example, the default will be prevented as long as the div has the .red class, the setTimeout will remove the class after 3 seconds.
JS:
$('body').on('click', '.red', function (e) {
e.preventDefault();
console.log('I only show up while default is prevented');
});
$('body').on('click', 'div', function () {
console.log('I will always show up');
});
setTimeout(function () {
$('div').removeClass('red');
},3000);

Click Function "this" not working

I have a script that I found at http://www.red-team-design.com/cool-notification-messages-with-css3-jquery, but I'm having a problem with my code
I'm wanting to get it to 1) hide on click, and 2) hide after 15 seconds
HTML:
<div class="warning message">It is currently past 4pm. Any orders placed between now and midnight will not be placed until 4pm tomorrow.</div>
Javascript:
var myMessages = ['info','warning','error','success']; // define the messages types
function hideAllMessages(){
var messagesHeights = new Array(); // this array will store height for each
for (i=0; i<myMessages.length; i++){
messagesHeights[i] = $('.' + myMessages[i]).outerHeight(); // fill array
$('.' + myMessages[i]).css('top', -messagesHeights[i]); //move element outside viewport
}
}
function showMessage(type){
hideAllMessages();
$('.'+type).animate({top:"0"}, 500);
setTimeout(function(){
$('.'+type).animate({top: -$('.'+type).outerHeight()}, 500);
hideAllMessages();
},15000);
}
$(document).ready(function(){
// Initially, hide them all
hideAllMessages();
// Show message
for(var i=0;i<myMessages.length;i++) {showMessage(myMessages[i]);}
// When message is clicked, hide it
$('.message').click(function(){
$(this).animate({top: -$(this).outerHeight()}, 500);
});
});
This is getting executed by php, which I'm just inserting the following line into my code using php:
<script type='text/javascript'>
$(document).ready(function(){
showMessage(warning)
});
</script>​
Now for some reason the div doesn't hide when I click it, and it won't hide after the 15 seconds as specified.
I've created a JSFiddle at http://jsfiddle.net/dpdesignz/yTaRa/1/ if anyone would mind looking to see what may be going wrong? I have a feeling it's related to the part executed by the PHP echo, so does anyone know of another way to maybe do this?
You have a few errors in your code.
First warning is not defined
Which refers to the following:
$(document).ready(function(){
showMessage(warning)
});
warning is not a set variable. Perhaps you mean this to be 'warning'.
Secondly showMessage is not defined
showMessage('warning');
This is called before the showMessage() function is defined. You can fix this by moving this call into the other $(document).ready()
http://jsfiddle.net/yTaRa/5/
var myMessages = ['info','warning','error','success']; // define the messages types
function hideAllMessages(){
var messagesHeights = new Array(); // this array will store height for each
for (i=0; i<myMessages.length; i++){
messagesHeights[i] = $('.' + myMessages[i]).outerHeight(); // fill array
$('.' + myMessages[i]).css('top', -messagesHeights[i]); //move element outside viewport
}
}
function showMessage(type){
hideAllMessages();
$('.'+type).animate({top:"0"}, 500);
setTimeout(function(){
$('.'+type).animate({top: -$('.'+type).outerHeight()}, 500);
hideAllMessages();
},15000);
}
$(document).ready(function(){
// Initially, hide them all
hideAllMessages();
// Show message
for(var i=0;i<myMessages.length;i++) {showMessage(myMessages[i]);}
// When message is clicked, hide it
$('.message').click(function(){
$(this).animate({top: -$(this).outerHeight()}, 500);
});
showMessage('warning');
});
​
$(document).ready(function(){
$('.info, .warning, .error, .success').hide();
$('.info, .warning, .error, .success').slideDown(500);
$('.info, .warning, .error, .success').delay(15000).slideUp(500);
$('.info, .warning, .error, .success').on('click', function() {
$(this).hide();
});
});
Let jQuery do all the work =)
http://jsfiddle.net/yTaRa/8/
If every message type will also be classed as message we can reduce this code down even further...
$(document).ready(function(){
$('.message').hide();
$('.message').slideDown(500);
$('.message').delay(15000).slideUp(500);
$('.message').on('click', function() {
$(this).hide();
});
});
http://jsfiddle.net/yTaRa/9/
$(document).ready(function(){
setTimeout(function() { //sets a 15 second timer on each message to collapse up over .5 seconds
$('.message').slideUp(500);
}, 15000);
$('.message').hide(); //hides all elements with the class message.
$('.message').slideDown(500); //animates messages to expand down over .5 seconds
$('.message').on('click', function() { //wires up click event to hide message on click
$(this).slideUp(500);
});
});
http://jsfiddle.net/yTaRa/10/
I had to use setTimeout for the 15 seconds call of slideUp as the click slideUp would not fire with:
$('.message').delay(15000).slideUp(500);
I assume that this is because only one slideUp() call can be scheduled on the same element at one time.

How to add a wait time before hover function is executed

I am working on a nested menu, and when my mouse move over a option, a sublist will show up.
Here is my hover function:
$( ".sublist" ).parent().hover( function () {
$(this).toggleClass("li_hover",300); //use to change the background color
$(this).find(".sublist").toggle("slide", {}, 500); //sub list show / hide
});
Now, I want add a short period before the sublist shows up to prevent the crazy mouse moving from user. Does somebody have a good suggestion on this?
Update:
Thanks for you guys, I did a little bit change on my program, recently it looks like this:
function doSomething_hover (ele) {
ele.toggleClass("li_hover",300);
ele.find(".sublist").toggle("slide", {}, 500);
}
$(function () {
$( ".sublist" ).parent().hover( function () {
setTimeout(doSomething_hover($(this)), 3000);
});
}):
This is weird that setTimeout will not delay anything. but if I change the function call to doSomething_hover (without "()"), the function will delay good. but i can not pass any jquery element to the function, so it still not works, could somebody tell me that how to make doSomething_hover($(this)) work in setTimeout ?
Update 2:
Got the setTimeout work, but it seems not what I want:
What I exactly want is nothing will happen, if the mouse hover on a option less than 0.5sec.
Anyway, here is the code I make setTimeout work:
function doSomething_hover (ele) {
ele.toggleClass("li_hover",300);
ele.find(".sublist").toggle("slide", {}, 500);
}
$(function () {
$( ".sublist" ).parent().hover( function () {
var e = $(this);
setTimeout(function () { doSomething_hover(e); }, 1000);
});
}):
Final Update:
I got this work by using clearTimeout when I move the mouse out.
so the code should be:
$( ".sublist" ).parent().mouseover( function () {
var e = $(this);
this.timer = setTimeout(function () { doSomething_hover(e); }, 500);
});
$( ".sublist" ).parent().mouseout ( function () {
if(this.timer){
clearTimeout(this.timer);
}
if($(this).hasClass("li_hover")){
$(this).toggleClass("li_hover");
}
$(this).find(".sublist").hide("slide", {}, 500);
});
This is the part in the $(document).ready(). Other code will be same as above.
真. Final Update:
So, mouseover and mouseout will lead to a bug sometime, since when I move the mouse to the sublist, the parents' mouseover event will be fire, and hide the sublist.
Problem could be solved by using hover function:
$( ".sublist" ).parent().hover(
function () {
var e = $(this);
this.timer = setTimeout(function () { doSomething_hover(e); }, 500);
},
function () {
if(this.timer){
clearTimeout(this.timer);
}
$(this).find(".sublist").hide("slide", {}, 500);
if($(this).hasClass("li_hover")){
$(this).toggleClass("li_hover",300);
}
}
);
Thanks all
Try this please:
Code
setInterval(doSomthing_hover, 1000);
function doSomthing_hover() {
$(".sublist").parent().hover(function() {
$(this).toggleClass("li_hover", 300); //use to change the background color
$(this).find(".sublist").toggle("slide", {}, 500); //sub list show / hide
});
}​
SetTime vs setInterval
At a fundamental level it's important to understand how JavaScript timers work. Often times they behave unintuitively because of the single thread which they are in. Let's start by examining the three functions to which we have access that can construct and manipulate timers.
var id = setTimeout(fn, delay); - Initiates a single timer which will call the specified function after the delay. The function returns a unique ID with which the timer can be canceled at a later time.
var id = setInterval(fn, delay); - Similar to setTimeout but continually calls the function (with a delay every time) until it is canceled.
clearInterval(id);, clearTimeout(id); - Accepts a timer ID (returned by either of the aforementioned functions) and stops the timer callback from occurring.
In order to understand how the timers work internally there's one important concept that needs to be explored: timer delay is not guaranteed. Since all JavaScript in a browser executes on a single thread asynchronous events (such as mouse clicks and timers) are only run when there's been an opening in the execution.
Further read this: http://ejohn.org/blog/how-javascript-timers-work/
timeout = setTimeout('timeout_trigger()', 3000);
clearTimeout(timeout);
jQuery(document).ready(function () {
//hide a div after 3 seconds
setTimeout( "jQuery('#div').hide();",3000 );
});
refer link
function hover () {
$( ".sublist" ).parent().hover( function () {
$(this).toggleClass("li_hover",300); //use to change the background color
$(this).find(".sublist").toggle("slide", {}, 500); //sub list show / hide
});
}
setTimeout( hover,3000 );
....
You could use .setTimeout
$(".sublist").parent().hover(function() {
setTimeout(function() {
$(this).toggleClass("li_hover", 300); //use to change the background color
$(this).find(".sublist").toggle("slide", {}, 500); //sub list show / hide
}, 1000);
});​

Issues with clearTimeout

I am trying to build a simple navigation with sub-navigation drop-downs. The desired functionality is for the drop-down to hide itself after a certain amount of seconds if it has not been entered by the mouse. Though if it is currently hovered, I would like to clearTimeout so that it does not hide while the mouse is inside of it.
function hideNav() {
$('.subnav').hover(function(){
clearTimeout(t);
}, function() {
$(this).hide();
});
}
$('#nav li').mouseover(function() {
t = setTimeout(function() { $('.active').hide()}, 4000);
//var liTarget = $(this).attr('id');
$('.active').hide();
$('.subnav', this).show().addClass('active');
navTimer;
hideNav();
});
What am I missing? Am I passing the handle wrong?
You should also clear the timeout in mouseover, before setting the new timeout.
Otherwise a timeout started before will still be active, but no longer accessible via the t-variable.
you can make the timer variable global.
function hideNav() {
$('.subnav').hover(function(){
clearTimeout(window.t);
}
}
$('#nav li').mouseover(function() {
window.t = setTimeout(function() { $('.active').hide()}, 4000);
});
Try doing it the recommended way (JS statement as a string):
t = setTimeout("$('.active').hide()", 4000);

Categories