Keir Simmons
Keir Simmons

Reputation: 1684

What is the proper method for creating dynamic hyperlinks in JavaScript?

I know it's frowned upon to create links such as <a href="javascript:my_func();">link text</a> as this tricks the user into thinking it's a real link.

I have quite a few links that actually just run JS code in the browser instead of forcing page navigation, and as such I don't want to use the above and am looking for an alternative that works in all browsers and prevents middle clicking from opening a new tab/ window.

Would the following approach be satisfactory?

HTML

<a href="javascript:void(0);" id="id_here">link text</a>

JavaScript

$("#id_here").bind('click',(function(params){
    return function(){
        // do stuff here with `params`
    };
})(params));

Upvotes: 2

Views: 240

Answers (4)

Eric
Eric

Reputation: 97661

I did some playing around, and you can get some good results with hashchange:

var commands = {
    foo: function() { alert("Foo!"); },
    bar: function() { alert("Foo bar!"); },
    baz: function() { alert("Foo bar baz!"); }
};

$(window).bind('hashchange', function() {
    var hash = window.location.hash.replace(/^#/,'');
    if(commands[hash]) {
        commands[hash]();
        return false;
    }
}).trigger('hashchange');​

With the simple HTML of:

<a href="#foo">Foo</a>
<a href="#bar">Bar</a>
<a href="#baz">Baz</a>​

This even works if you right click -> open in new tab or middle click!


Note that hashchange is not supported by all browsers.

Upvotes: 0

Viktor S.
Viktor S.

Reputation: 12815

<a href="#" id="id_here">link text</a>

# is here to make a link look like link JavaScript:

$("#id_here").bind('click',function(e){
    e.preventDefault();
})

e.preventDefault() does not allow browser to execute default action (like navigate to another page)

Upvotes: 0

JCOC611
JCOC611

Reputation: 19759

I would recommend you used another node other than <a>, such as a <div>:

<div id="jsLink" style="cursor:pointer">Click Me</div>

and jQuery:

$("#jsLink").click(function(params){
  // do something
}

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191799

javascript: anything is bad. There isn't much difference between the two javascript: uses above. Using "#" for the href is about as bad; it adds to the history with JS off and the link is not useful. What you should do (ideally) is have the link actually work, e.g.

<a href="/an/actual/path"> ...

Then, with JS, prevent default link behavior

$("#id_here").on('click', function (e) { e.preventDefault(); });

If there is no actual path to go to, then the link should not even be exposed with JS off; you can either append it to the DOM later or just hide it with CSS (and show it with JS).

Upvotes: 3

Related Questions