Trap browser close event in javascript

many times we need to perform some task once user close the browser. You can user the following code for the same .

function HandleOnClose(e)

{

var ieversion=0;

if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))

{

ieversion=new Number(RegExp.$1)

}

if (ieversion<7)

{

if (window.event.clientX < 0 && window.event.clientY < 0)

{ DoSomething(); }

}

else if (ieversion>=7)

{

if (isBrowserClosed())

{ DoSomething(); }

}

}

function isBrowserClosed()

{

var browserWindowWidth = 0;

var browserWindowHeight = 0;

// gets the width and height of the browser window

if (parseInt(navigator.appVersion) > 3)

{

if (navigator.appName == “Netscape”)

{

browserWindowWidth = window.innerWidth;

browserWindowHeight = window.innerHeight;

}

if (navigator.appName.indexOf(“Microsoft”) !=- 1)

{

browserWindowWidth = top.window.document.body.offsetWidth;

browserWindowHeight = top.window.document.body.offsetHeight;

}

}

// checks if the X button was closed

// if event.clientY < 0, then click was on the browser menu area

// if event.screenX > (browserWindowWidth – 25), the X button was clicked

// use screenX if working with multiple frames

return (event.clientY < 0 && event.screenX > (browserWindowWidth – 25)) ? true : false;

}

function DoSomething()

{

// do your task here

}

Advertisements

Get Source Element on OnClick Event Raised

While developing web applications we don’t know the id of the control many times (mostly when controls are added dynamically ) .In JavaScript we can get the control and its properties on On Click event of the control.

 HTML Code

 

<button name=’<%# Eval (“ProductName”) %> value=”Open” onclick=”javascript:test();”>Open</button>

 Javascript Code

<script type=”text/javascript” language=”javascript”>function test(){
 

var tag;

tag=“Element name: “ + window.event.srcElement.tagName + ” ID: “ + window.event.srcElement.id;

document.write(tag);

}

 </script>