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.
Related
I am having some trouble with the on before unload and the unload method. I thought i set the code right in terms of the onload method only firing up after the confirm method for onbeforeunload was set a true. but sadly that isn't the case, what is happening is the unload method is starting even if the onbeforeunload method is set to false and the person wants to stay at the website. Here is the code I am working on it has changed a lot since I started hope its okay. I am sure it isn't since its not working the way I want it to.
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 does not work like you think it does. You can return a string from the handler, which will prompt a messsage, or undefined which will do nothing.
window.onbeforeunload = goodbye;
function goodbye(e) {
if (!validNavigation) {
return leave_message;
} else {
return undefined;
}
}
Related: Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?
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);
I have a JavaScript event listener function that waits for a user to click on any link then shows a loading box then progresses onto next page.
If a user then clicks the back button it still shows the loading box? Is there a way I can remove it without having to force refresh?
function loading_show() {
document.getElementById("loading").removeAttribute("style");
}
// Function to add event listener to t
function load() {
var el = document.getElementsByTagName("a");
for (var i = 0; i < el.length; i++)
{
el[i].addEventListener("click", loading_show, false);
}
}
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// do stuff
load();
};
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
clearInterval(_timer);
init(); // call the onload handler
}
}, 10);
PS. I'm developing for a mobile environment and I don't wish to use jQuery so don't suggest it please.
You can try catching it with the "beforeunload" event.
Here's how to use it:
catching beforeunload confirmation canceled?
Ok, firstly, I hardly know Javascript. I really don't know what I'm doing.
So, I have this code:
var interval_id = 0;
var prevent_bust = 0;
// Event handler to catch execution of the busting script.
window.onbeforeunload = function() { prevent_bust++ };
// Continuously monitor whether busting script has fired.
interval_id = setInterval(function() {
if (prevent_bust > 0) { // Yes: it has fired.
prevent_bust -= 2; // Avoid further action.
// Get a 'No Content' status which keeps us on the same page.
window.top.location = 'http://vadremix.com/204.php';
}
}, 1);
function clear ()
{
clearInterval(interval_id);
}
window.onload="setTimeout(clear (), 1000)";
After 1 second I want to clear the interval set earlier. This isn't working. How would I do what I'm trying to do?
If you substitute the last line with window.onload = function() { setTimeout(clear, 1000); }, it should do OK.
There are two errors in your code:
window.onload should be a function, rather than a string ("..."),
setTimeout accepts a function (clear), rather than the result from the function (clear())
By the way, these are some good places to learn JavaScript:
QuirksMode
Mozilla Developer Network
I have a function that updates a <div /> via AJAX:
function update() {
<!-- .ajax() -->
setTimeout(update(), 3000);}
}
What I need is that this is not executed when the user is not present on the website, so if there is no movement of the mouse (we will suppose that if move it is in the website) it will not update .mousemove(). By the way, there is any other thing that we can do to know is someone is active on the website?
How can this be done? Thank you in advance!
Edit: probably I explained bad. I need to know the way to only update when there is activity. Like Facebook does with his news feed, the front page. Thanks!
You could use a mousemove handler to track when the user last moved, and then have the process only happen if they last moved the mouse within X seconds. But of course, if the user is sitting there reading something, or if they're a keyboard-oriented kind of person, that will tend to miss that they are there... So you'd probably want to look at keydown as well.
Here's a mousemove example:
jQuery(function($) {
var count = 0, lastmove = new Date();
$(document).mousemove(function() {
++count;
lastmove = new Date();
$('#display').html("Moved " + count + " times");
});
});
Then your update code could do this:
function update() {
if (new Date() - lastmove < 60000) { // 60 seconds
// Really do the update
}
else {
// Check back in a few seconds
setTimeout(update, 3000);
}
}
Off-topic, but you have an error in your update code. You have:
setTimeout(update(), 3000);
...which will call update immediately and then try to use its return value to schedule something to happen in three seconds. If you want the call to update to be scheduled to happen in three seconds, leave off the () after it:
setTimeout(update, 3000);
I think I might have ended up with something such as this. Avoids date arithmetic. Only cares whether there's been some activity since the last update().
window.activeFlag = false;
window.updateDelay = 3000;
$(document).bind('mousemove scroll keydown', function(){ activeFlag = true; });
function update() {
if(activeFlag) {
doWork();
activeFlag = false;
}
}
window.setTimeout(update, updateDelay);
edit: I've discovered a flaw in the code. The following is more appropriate:
window.activeFlag = false;
window.updateDelay = 3000;
$(document).bind('mousemove scroll keydown', function(){ activeFlag = true; });
function update() {
if(activeFlag) {
doWork();
activeFlag = false;
}
window.setTimeout(update, updateDelay);
}
update();
I think there is no easy way to determine if the user is present
I would use a combination of mousemove, scroll, keypress.
var bUpdate = false;
function update() {
if(bUpdate){
///perform your ajax request
}
}
$(document).mousemove(function(){
bUpdate = true;
setTimeout(function(){bUpdate=false;}, 3000);}
});