Modify target url in onclick handler

TMS picture TMS · Mar 29, 2012 · Viewed 32.7k times · Source

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;
});

Answer

Gourneau picture Gourneau · Mar 29, 2012

Try

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