Undefined
Undefined

Reputation: 1929

Stop href link after onClick function is called

I have a link:

<h2><a href=?p=article&aid='.$article->id.'" onclick="loadPage('article'); return false;">.$article->title.</a></h2>

and it calls this function:

function loadPage(page){
    $("#content").html("Loading...");

    $.post("page.php", {p: page}, function(data){
        $("#content").html(data);   
    });
}

But after my javascript has been ran the href is still active. I've used return false; on my onClick's before to prevent this but it's not working this time????

Upvotes: 3

Views: 9909

Answers (3)

Phil
Phil

Reputation: 4224

It looks like your script has an error and is not reaching the return block. If you add the try catch, it will ignore the errors in the script.

function loadPage(page){
try{
    $("#content").html("Loading...");

    $.post("page.php", {p: page}, function(data){
        $("#content").html(data);   
    });
} catch(err){}
}

Upvotes: 1

andyb
andyb

Reputation: 43823

You might be better off using jQuery to bind the click event to your function, as the logic is better separated.

$('h2 a').click(function(event) {
    $("#content").html("Loading...");

    $.post("page.php", {p: page}, function(data){
        $("#content").html(data);   
    });

    return false;
});

Usually, if the href is still active is it likely that there was a JavaScript error.

Edit: You could also use event.preventDefault() to stop the href being followed with the click function bound in this way.

Lastly, the href does seem very well formed (missing an opening quote). Is that a typo?

Upvotes: 1

Felix
Felix

Reputation: 801

My favorite way to do this is to replace the href attribute. This has the advantage of preserving compatibility with non-JS clients, and not having to deal with 'stopping' the event or any such wizardry. For example:

function unobtrusiveLinkSetup(link) {
    // replace the about link's href
    J(link).attr('jshref', J(link).attr('href'));
    J(link).removeAttr('href');

    // handle the link's action
    J(link).click(function(index) {
            J(this).stop();
            // make a request in the background
            J.get(J(this).attr('jshref'), function(result) {
                // whatever you need to do with the link..
            });
    });
}

Then you can just do unobtrusiveLinkSetup("#myLink"); in your document's ready function, or wherever else.

Upvotes: 1

Related Questions