js onbeforeunload event – alert before leaving the page

if you wan”t to prevent a user from leaving your page,
something you might wanna do if you build a cms , or some admin page with user changing fields.

create a javascript variable named isDirty and make sure that field will be set to true on all input changes on the page (and some non trivial changes you might have in your ui)
than bind an event to the window.onbeforeunload (works on all browsers without the use of an extrenal js lib such as jQuery, dojo, mootools)

 window.onbeforeunload = function (ev) {
            var leavePageMsg = ''Your changes haven\''t been saved.\nAre you sure you want to leave this page?'';
            ev = ev || window.event;
            if (isDirty) {
                if (ev) {
                    ev.returnValue = leavePageMsg;
                return leavePageMsg;
            // no return value - meaning it''s ok to leave the page.

Thats it, it will do the magic :)
Have a good one.

Posted in HTML, javascript

Leave a Comment