Search code examples
javascriptjqueryhref

Modify target url in onclick handler


Is it possible to modify the target URL in the onclick handler? How?

I don't want to use things like window.location = ... because it changes the browsers' behaviour (click vs ctrl-click, opening in new tab, opening in particular window/frame etc...). I want a clean solution - just change the url and the rest should be done itself as it would normally be.

$(...).click(function () {
    if (check_some_condition) 
        // modify target url here...
        // do not want to do window.location= - this is not clean
        // as it changes the browsers' behaviour (ctrl-click, opening in particular window/frame etc.)
    return true;
});

Solution

  • Try

    ​$(function(){
        $("#theLink").click(function(){
            $(this).attr("href","http://tnbelt.com");
        });
    });​​​​