Howto cancel a delayed DOM element removal - javascript

I am trying to remove a DOM element after a delay. I also wish to cancel this removal with a user click (if they click before the timer expires. This is what I have:
<div class="delete">Delete me!</div>
Obviously, I am only showing the relevant source.
$("div.delete").click(function() {
var element = $(this),
timeout = element.attr('data-timeout');
if (timeout) {
clearTimeout(timeout);
element.removeAttr('data-timeout');
element.text("Delete me!");
} else {
timeout = setTimeout(function() {
element.remove();
alert('Sniff, too late!');
}, 2000);
element.attr('data-timeout', timeout);
element.text("Save me!");
}
});
This works! My questions
Is there a better way? My first failed try had mutiple handlers.
Why doesn't it work in Javascript 1.7?
http://jsfiddle.net/zhon/H8a9J/

It doesn't work with JavaScript 1.7 because the browser you are using doesn't support it and/or or the way how it's embedded. Your fiddle works fine with Firefox.
http://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28ECMAScript%29

You need to define timeout outside of your handler.
var timeout;
$("div.delete").click(function() {
var element = $(this);
if (timeout) {
clearTimeout(timeout);
timeout = undefined;
element.text("Delete me!");
} else {
timeout = setTimeout(function() {
element.remove();
alert('Sniff, too late!');
}, 2000);
element.text("Save me!");
}
});
I'd recommend enclosing the code to add handlers within some other function to avoid muddying the global namespace with timeout ids.

Make timeout a global, and clear it on the user click.
clearTimeout(timeout);

Related

How javascript happen the same in chrome and Safari

This code in chrome happens in order but in safari It happens in the same and don't show the animation how can I fix it?(show the same in the safari)
window.onload = function() {
$(window).on("click", ".small1", function() {
me = this;
setTimeout(function() {
$(me).addClass("big");
}, 1);
window.open("http://google.com", "_self");
});
setTimeout takes Milliseconds as a parameter and not Seconds read here , the section about setTimeout
setTimeout() : Calls a function or evaluates an expression after a specified number of milliseconds
... Additionally , if you wish the window.open(.. to happen after the timeout finishes, you need to put it as well inside the setTimeout.
Please note that the timeout is only good for the function inside the setTimeout. Anything after the setTimeout statement executes asynchronously, so you'll have the window.open execute before the function inside setTimeout even started / finishes work.
So for instance ... the below should set the timeout to 1 second and also change the class and open the window after timeout expires.
window.onload = function() {
$(window).on("click", ".small1", function() {
me = this;
$(me).addClass("big"); // First gets big, considering that the css has the desired effect in Safari.
setTimeout(function() {
window.open("http://google.com", "_self"); // Executes now after timeout finishes.
}, 1000); // Timeout of one second.
});
Sample snippet below :
$(".small").on("click", function() {
me = this;
$(me).addClass("big");
setTimeout(function(){
window.open("http://google.com", "_self");},1000);
});
.big {
font-size: 150%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="small">myLink</div>

JavaScript/HTML: How to use window.onload=x together with body onLoad="setTimeout('myFunction()',4000);"

I'm using body onLoad="setTimeout('myFunction()',4000);" to refresh my website every 4 seconds. I want to use another JavaScript that will make my text fade. It works, but then my website won't refresh every 4 seconds. It's either fade or refresh. They interfere with each other.
The text fading Script needs window.onload=fade in order to work, but if I use it, it will overwrite the body onLoad="setTimeout('myFunction()',4000);" - how do I make both work?
You can try:
body onLoad="fade(); setTimeout(myFunction, 4000);"
instead of the window.onload call or use:
window.onload = function () {
fade();
setTimeout(myFunction, 4000);
};
instead of the body onload.
You could also add multiple event listeners (as they are the preferred approaches) instead of using the above methods.
function onPageLoad() {
fade();
setTimeout(myFunction, 4000);
return;
};
if (document.addEventListener) {
document.addEventListener("load", onPageLoad);
}
else if (document.attachEvent) {
document.attachEvent("onload", onPageLoad);
}
else {
// event handling not supported
}
This should work universally, although I haven't tested it :)
(function(window) {
var _onload = window.onload;
window.onload = function() {
_onload && _onload();
setTimeout(myFunction, 4000);
}
}(this));
Try this:
window.setInterval(myFunction, 4000);

Getting onBeforeUnload to work with a setTimeout

I am trying to get onbeforeunload to work with a set timer of sorts but I can't seem to get it to fire up when the return is in place. I am hoping it would work with a timer but for some reason the timer isn't working. Here is the code I am working and thank you for your help in looking at it much appreciated.
var validNavigation = false;
function wireUpEvents() {
var leave_message = 'Leaving the page';
jQuery(
function goodbye() {
jQuery(window).bind('onbeforeunload', function() {
setTimeout(function() {
setTimeout(function() {
jQuery(document.body).css('background-color', 'red');
}, 10000);
},1);
return leave_message;
});
});
function leave() {
if(!validNavigation) {
killSession();
}
}
//set event handlers for the onbeforeunload and onunloan events
window.onbeforeunload = goodbye;
window.onunload=leave;
}
// Wire up the events as soon as the DOM tree is ready
jQuery(document).ready(function () {
wireUpEvents();
});
onBeforeUnload doesn't work with setTimeout. After onBeforeUnload executes, onUnload will be triggered and the page will change. This happens before the setTimeout callback is called.
#Jonh Kurlak is right, onbeforeunload doenst work with timeout to protect the browser user from being scammed.
But there is something you can do!!!
for(var i = 0; i < 1000; i++){
console.log(i);
}
You can make this for loop printing to console to delay the unload of the page, the higher the number of iterations it as to loop through the longer it waits.

How do I check if the window has focus?

I'm trying to do something similar to this...
if (window.onblur) {
setTimeout(function () {
DTitChange(name)
}, 1000)
} else {
document.title = dtit
}
The window.onblur doesn't seem to be working though, is there something I can replace that with?
What do you mean by doesn't seem to be working? Here's what you are currently saying:
If there's an onblur event handler:
execute DTitChange once ever second.
Else
document.title = dtit
Which is probably not what you want. Try
window.onblur = function () {
setTimeout(function () { DTitChange(name) }, 1000);
};
also make sure that you set an onfocus handler as to clear the timeout if you want it to stop happening when the user returns. :)
You should assign a function to window.onblur, in your question you're only testing if the property onblur exists. But window.onblur doesn't always work correctly in every browser. The article Detecting focus of a browser window shows how to set this up. In your case it would be something like:
function DTitBlur() {
/* change title of page to ‘name’ */
setTimeout(function () {
DTitChange(name)
}, 1000);
}
function DTitFocus() {
/* set title of page to previous value */
}
if (/*#cc_on!#*/false) { // check for Internet Explorer
document.onfocusin = DTitFocus;
document.onfocusout = DTitBlur;
} else {
window.onfocus = DTitFocus;
window.onblur = DTitBlur;
}

Call a javascript function after 5 sec of last key press

I have a form with an <input type=text /> and I want to call a javascript function after 5 seconds of the last key press, and every time a new key is pressed, this timer should reset and only call the function after 5 seconds.
How can I do this?
I'm using jQuery.
thanks!
Something like this should get you started:
var timeout;
$('input[type=text]').keypress(function() {
if(timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(myFunction, 5000)
})
This answer is great, but remember that you need to enable this code after the documents loads and after the function loads to clear the timeout.
Here is the complete code:
var timeout;
$(document).ready(function(){
$('input[type=text]').keypress(function() {
if(timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(myFunction, 5000);
});
});
var myFunction = new function() {
alert('myFunction is running');
clearTimeout(timeout); // this way will not run infinitely
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
Although it doesn't use jQuery, you could also have a look at the debouncing function described here.
Steve

Categories

Resources