Zaki
Zaki

Reputation: 5600

Javascript in master page not firing

I have a javascript function for confirmation :

function confirm() {
    var answer = confirm("Are you sure you want to log out?")
    if (answer) {
        return true;
    }

    return false;
} 

and on my link I call this function :

<div class="header">
                <a href="" class="logo"></a>
                <div class="topToolbar">
                    <span><a href="/Logout.aspx" onclick="return confirm();">Log Out</a></span>
                </div>
            </div>

The issue is that it never calls the javascript function, tried to put alerts and didnt get anything.

I even tried to do it with jquery bt still same thing the only difference was that I could get alert on document ready function.

Upvotes: 0

Views: 297

Answers (2)

slashnick
slashnick

Reputation: 26559

You are not calling the function in the onclick, you need to rename the function so it doesn't clash with confirm.

logoutMessage = function() {
    var answer = confirm("Are you sure you want to log out?")
    if (answer) {
        return true;
    }

    return false;
} ​

<div class="header">
    <a href="" class="logo"></a>
    <div class="topToolbar">
        <span><a href="/Logout.aspx" onclick="return logoutMessage()">Log Out</a></span>
    </div>
</div>​

Ideally you wouldn't use the onclick attribute in the html. You can keep it purely in the javascript by using an event listener, which is clearer and avoids have to pollute the markup. If you give the logout link an id you can do:

document.getElementById("logout").addEventListener("click", logoutConfirm);

That will call the function on click.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039598

You should rename your function. confirm is reserved for, well, the confirm function:

function shouldContinue() {
    return confirm("Are you sure you want to log out?");
}

and then:

<a href="/Logout.aspx" onclick="return shouldContinue();">Log Out</a>

Actually to be more precise confirm is not a reserved keyword. You could override the confirm function. And that's what you did. Except that inside this overridden function you called it once again and thus ending in a recursive endless loop.

Here's an example how you could override it:

window.confirm = function(msg) {
    alert('this is the overriden confirm function');
    return true;
};

Upvotes: 6

Related Questions