Jquery event doesn't fire in any case - javascript

So, here I want just to alert true, when window is closed ( I mean particullary tab in browser).
$(document).ready(function(){
});
$(window).unload(function(){
alert('true'); });
tried $(window) also inside $(document).ready(), nothing.

You're very limited in what you can do in the context of window.unload. The browsers won't let you do anything to force the user to stay on the page, and that includes calling alert.
The best thing you're allowed to do is return a string from an onbeforeunload handler - the browser will display that to the user, along with a question like "Are you sure you want to leave this page?"

Related

Set focus on unloading window at onunload

I have got a confirm dialog at the onunload event. It works well but there is only one problem: the window loses at onunload the focus and passes it automatically to the parent. But since there is still the confirm dialog going on I don't want to lose the focus on this window.
I have already tried to set the focus manually with window.focus() but this isn't working.
At the moment my code for the onunload event looks like this:
window.onunload = sessionConfirmation;
function sessionConfirmation(e) {
window.focus();
confirm('test');
}
Thank you in advance!
Not quite sure what your end-game is, but I'm assuming you want a confirmation dialog to show when the user tries to leave the page. If so, you want to do this instead:
window.onbeforeunload = sessionConfirmation;
function sessionConfirmation(e) {
return "test";
}
Hope that's what you were asking for!

Custom confirm box that has some functionality to it with window close event

I'm presently writing JavaScript, on clicking the close button in the window, I should get a confirm box. In the confirm box, I should display some message and there should be cancel and continue buttons.
On clicking cancel, the window should not be closed, but on pressing continue, the window should be redirected to another jsp.
Can someone please help me with this code? I tried using the custom confirm box, but that seems to return only a string and it cannot be used to redirect to a page.
This is impossible. You cannot redirect the user to another page when they close the window. This is for security reasons.
To display a confirm box when closing the window, you can use the onbeforeunload event. This will ask the user if they wish to leave the page or not. The confirm box is rendered by the browser, all you can customize on is the text.
$(window).bind('beforeunload', function(){
return 'Are you sure you want to leave?';
});
When the user leaves the page, you can use the onunload event, but again, you cannot redirect them (you can make an AJAX call, but you cannot redirect the browser).
$(window).bind('unload', function(){
console.log('bye'); // Some browsers may block this.
// Chrome blocks alerts in this event.
});
check this example it may help you out
function setConfirmUnload(on){
window.onbeforeunload = (on) ? unloadMessage : null;
}
function unloadMessage(){
return "Are you sure you want to leave this page";
}
setConfirmUnload(true) to enable the confirmation or false if you want to allow them to close the screen without a warning (if you have a close button for instance).
You can try also this (link : http://api.jquery.com/unload/)
$(window).unload(function(){
alert("Bye now!");
});
You need to bind a handler to the onBEFOREunload event, as none of the functionality you want will be possible with the onunload event (it is too late).
var myFunction = function () {
return "Are you sure you want to leave the page?";
};
window.onbeforeunload = myFunction;
As far as I know, there is no way to react to the user input as the confirm box is handled by the browser.

what can i put in beforeUnload?

I would like to have an animation effect which starts when people leave a page.
I use this currently:
window.onbeforeunload = function (){
alert("test");
console.log("test");
sliderIntervalId = setInterval('SlideDown()',1);
}
While the "test" is indeed logged to the console, the neither the function slideDown nor the test alert is produced...
Is this normal behavior? can we use the beforeunload function only for backend purposes?
P.S. I'm testing on chrome, that's why I had to use onbeforeUnload i.s.o onUnLoad which seems not to be supported by Chrome?
onbeforeunload can delay the page unload in only one case: When a return statement with a defined value is returned. In this case, the user gets a confirmation dialog, which offers the user an option to not leave the page.
Your desired result cannot be forced in any way. Your animation will run until the browser starts loading the next page:
[User] Navigates away to http://other.website/
[Your page] Fires `beforeunload` event
[Your page] `unload` event fires
[Browser] Received response from http://other.website/
[Browser] Leaves your page
[Browser] Starts showing content from http://other.website/
Assuming jQuery for the sake of brevity:
$('nav a').click(function (e) {
//ignore any "modified" click that usually doesn't open in the current window
if (e.which > 1 || e.shiftKey || e.altKey || e.metaKey || e.isDefaultPrevented()) {
return;
}
//where you going here?
var place = this.href;
//you're not going anywhere, buddy
e.preventDefault();
//watch me dance, first
$('.animate-me').fadeOut(1000, function afterAnimation () {
//you're free to go!
document.location = place;
});
});
Basically, you don't use onbeforeunload. One advantage is that you can keep the user as long as you want, one disadvantage is that the user won't see an animation when using a link outside nav (but you can just change the selector)
Obviously keep the animation fast, like suddenlyoslo.com do.
Jorrebor,
If your trying to have this animation fire when they leave your site or close the browser it will not work as intended. However, you can create this animation while the user travels within your site by removing the 'href' property of your links and creating animations that have a callback function that set the window.location property. Something like:
document.getElementById('home').onclick(function(){
yourAnimationFunction(function(){
window.location="example.com";
});
});
alot of work and wont be seo friendly however
I am working with onbeforeunload and What I was able to figure out is:
onbeforeunload handler is blocking the browser from destroying the current page
if you don't return anything, the popup does not appear.
So your code will be working as long as the event handler runs.
This means that timer functions are not usable. They just add to the execution queue, so anything they would do is being queued after the end of currently running handler, which is after the last point in time you were guaranteed your code is still running.
So there is only one way to stop the browser from unloading before the animation finishes:
put a blocking loop that wastes some time in the beforeunload handler
start CSS3 animation by setting an appropriate class on the element before the loop
make the loop end when the animation finishes (make the loop check the actual height of an element or something)
Oh, and yes, this is a nastiest hack of all, but I was able to find a way to stop the browser from unloading the page, right?
I would appreciate comments with ideas on what to put in the loop.
I am taking some options into account:
wasting CPU on come math on large numbers
accessing localstorage (synchronous call, IO operration)
accessing DOM (this solution already has to)
Any ideas?

Best practice for warning the user they will lose data

I have a site which uses a lot of JavaScript (mainly jQuery) and I need a nice global way to let the user know that they will lose unsaved changes when they navigate away from a particular page.
At the moment I have an onchange event placed on the inputs and wrap my main navigation in a function which will display the warning when clicked.
This feels really clunky and doesn't scale well (navigation which is not part of the main navigation needs to be manually wrapped, which is far from ideal)
I have an onchange event on my inputs and set an isDirty variable to true when they change.
Then I use onbeforeunload event to warn the user about unsaved changes:
var isDirty = false;
window.onbeforeunload = function (evt) {
if (isDirty) {
return 'If you continue your changes will not be saved.';
}
}
You are looking for the onbeforeunload event.
like
$(window).bind('beforeunload', function(){
return "Are you really sure?";
});
native:
window.onbeforeunload = function(){
return "Are you really sure?";
});
That of course is just the "preventing method". You still need some logic to know whether or not there were changes on your site. That could easily be done by using a boolean for instance. Furthermore you should make a quick detection like
if('onbeforeunload' in window){}
I think all major browsers support the event nowadays, but there are still browser which don't know that event. So if the above condition fails, you can still fallback gracefully to another way.
Use on the on unload window event to catch when the page is going to change. Then prompt a lightbox alert to warn the user if navigating away any unsaved data will be lost.

Can I override onbeforeunload for a particular element?

I have a page which does quite a bit of work and I don't want the user to be able to navigate away from that page (close browser, hit back button, etc.) without getting a warning. I found that the onbeforeunload event (which I think is IE-specific, which works fine for me as the project uses lots of ActiveX) works great.
Problem is, I want the user to be able to click on a little "help" icon in the upper-right corner and pop up a help window at any time. This causes onbeforeunload to fire, even though the main window never goes anywhere and the page never unloads.
The JavaScript function that runs when the onbeforeunload event runs just puts text into event.returnValue. If I could ascertain, somehow, that the help icon is the one that was clicked then I could just not put text into event.returnValue in that situation. But how could I have the page figure that out?
Let me guess: the help "icon" is actually a link with a javascript: url? Change it to a real button, a real link, or at least put the functionality in an onclick event handler (that prevents the default behavior). Problem solved.
<!-- clicking this link will do nothing. No onbeforeunload handler triggered.
Nothing.
And you could put something in before the return false bit...
...and the onunload handler would still not get called... -->
blah1
<!-- this should also do nothing, but IE will trigger the onbeforeunload
handler -->
blah2
EDIT: My "workaround" below is complete overkill, based on my lack of understanding. Go with Shog9's answer above.
OK so while I was writing the question, I came up with a workaround which will work for now.
I put a global JavaScript variable in act as a boolean on whether or not the icon is being hovered over. Then, I attach events to the image's onmouseover and onmouseout events and write functions that will set this value. Finally, I just code in the function that handles onbeforeunload that will check this value before setting event.returnValue.
Probably not a flawless workaround but it will work for now.
on the internet you will find many people suggesting you use something like
window.onbeforeunload = null
but this does not work for me in IE6. reading up in the MSDN docs for the event object i found a reference to the event.cancelBubble property, which i thought was the solution. but thanks to Orso who pointed out that setting "event.cancelBubble=true" is useless, the way to get rid of the confirm prompt is to exclude the return statement altogether, i chose to use a boolean variable as a flag to decide whether to return something or not. in the example below i add the javascript code programattically in the code behind:
Page.ClientScript.RegisterStartupScript(typeof(String), "ConfirmClose", #" <script> window.onbeforeunload = confirmExit; function confirmExit() { if(postback == false) return ""Please don't leave this page without clicking the 'Save Changes' or 'Discard Changes' buttons.""; } </script>");
then the help button contains the following aspx markup:
OnClientClick="postback=true;return true;
this sets the 'postback' variable to true, which gets picked up in the confirmExit() function, having the effect of cancelling the event.
hope you find this useful. it is tested and works in IE6 and FF 1.5.0.2.
I have a method that is a bit clunky but it will work in most instances.
Create a "Holding" popup page containing a FRAMESET with one, 100% single FRAME and place the normal onUnload and onbeforeUnload event handlers in the HEAD.
<html>
<head>
<script language="Javascript" type="text/javascript">
window.onbeforeunload = exitCheck;
window.onunload = onCloseDoSomething;
function onCloseDoSomething()
{
alert("This is executed at unload");
}
function exitCheck(evt)
{
return "Any string here."}
</script>
</head>
<frameset rows="100%">
<FRAME name="main" src="http://www.yourDomain.com/yourActualPage.aspx">
</frameset>
<body>
</body>
</html>
Using this method you are free to use the actual page you want to see, post back and click hyperlinks without the outer frame onUnload or onbeforeUnload event being fired.
If the outer frame is refreshed or actually closed the events will fire.
Like i said, not full-proof but will get round the firing of the event on every click or postback.

Categories