0

When I click on Logout link, my logout.php file is called which logs me out.

<a href=logout.php>Logout</a>

How can I call following javascript function before calling the logout.php file on the click of the Logout link.

Javascript function

function callMeBeforeLogout()
{
    alert("Do you really want to logout?");
}
3
  • 2
    You have to add onclick event handler: <a href=logout.php onclick="callMeBeforeLogout()"> Commented Apr 5, 2014 at 6:59
  • Add onclick event and for href you may want to use javascript:;. Commented Apr 5, 2014 at 7:01
  • @hindmost - your solution worked in the first attempt :) Commented Apr 5, 2014 at 7:07

3 Answers 3

5

I prefer an unobtrusive approach

<a href="/logout" id="logout-link">logout</a>

Then add the script

<script>
  var logoutLink = document.getElementById("logout-link");

  logoutLink.addEventListener("click", function(event) {
    if (confirm("Do you really want to logout?")) return;
    event.preventDefault();
  });
</script>

If the user clicks "OK", they just follow the href provided in the original link (/logout)

If the user clicks "Cancel", the confirmation dialog will go away, and nothing happens.

If the user has JavaScript disabled, the link will work, just without confirmation dialog.

Sign up to request clarification or add additional context in comments.

3 Comments

How did you use logoutLink?
refactor: confirm('logout?') ? function(){return} : event.preventDefault();
@bprayudha, I changed it a little bit.
3

try add onclick event

<a href="javascript:void(0);" onclick="callMeBeforeLogout();">Logout</a>

function callMeBeforeLogout() {
  alert('hi i m here');
}

if you want to redirect use window.location or window.location.href

Comments

1

Try like

<a href="javascript:;" onclick="callMeBeforeLogout();">Logout</a>

And in your function you have to write like

function callMeBeforeLogout()
{
    var cnfrm = confirm("Do you really want to logout?");
    if(cnfrm) {
        // here redirect to `logout.php`
        window.location.href = 'logout.php';
    }
}

3 Comments

Exactly how I would have suggested.. +1
@Fr0zenFyr ;-) but my ans was 3mins before your comment
I know, hence I didn't repeat an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.