user1805998 user1805998 - 7 months ago 11
HTML Question

Alert While moving to another page

I have an application where people can take on line test , When the user moves to another page the page should alert like you may lost the details if u go out of the page...
I tried of

window.unload()
but what i need is it should show alert only when the user moves to another page

Ex : My Page id
test.php

if user clicks next button for next question the page will redirect to
test.php?queNumber=2

so when the redirection happens to test.php it should not show alert if it redirects to other page like about.php or help.php it should alert , How to achive this ???

Thanks in advance

Answer

You can assign an event to all anchors in the page. And this event should check if anchor's href contain 'test.php' or not.

Try the following code:

$('a').click(function(event) {
   var href = $(this).attr('href');
   if(href.indexOf('test.php') == -1) { //if href does not contain test.php
      event.preventDefault();
      alert('You are about to leave');
   }
});