Tutorial :Is there a better (more efficient) way to run an href?


I was wondering if there's a better way to execute a link's href attribute other than evaling it?

For example:

eval($("a[href^=javascript:]").attr("href").replace(/^javascript:/,"")); // better (more eficient) way to do this?  



If you're talking about arbitrary JS code embedded in a href="javascript:window.open('blah')" style link, then not really.

You should clarify the question though - hrefs on anchor tags are really meant to be links to other documents, and you don't run them, you navigate to them. All you're really asking in your question is how to execute arbitrary javascript code supplied as a string, which is both more accurate and makes the answer clearer. (If you try to eval a standard URL href attribute, nothing interesting will happen.)

If you did mean "how do I get the same behaviour that would happen if I clicked on this link", then that's pretty complex. There's no specific way to do it, so you have to try to emulate the effects by reading the attributes of the link and synthesizing an equivalent action in Javascript. If you forget to inspect the target attribute, for example, this just won't work the same, and I'm sure there are lots of other pitfalls too.


Javascript should execute in the url bar as well, not unlike a bookmarklet. Try setting it to window.location without removing the 'javascript:'

window.location = el.attr("href");  


If you're trying to execute Javascript on an a tag, it's better to use an onclick attribute on the a tag in the first place. That way you can do $("a#whatever-link").click(); to get the same result.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »