newtogit
newtogit

Reputation: 553

How to correctly set an URL calling a javascript function?

I am using jslint to check my javascript.

It's giving me repeatedly the following error:

Problem at line 236 character 18: Script URL.
a.href = "javascript:DoSomething(" + messageID + ");"

Probably, jslint is right. What would be the correct way to set the .href?

Upvotes: 3

Views: 3278

Answers (6)

Roman Goyenko
Roman Goyenko

Reputation: 7070

to set: document.getElementById('myHref').href = "http://stackoverflow.com"

Upvotes: 0

Pointy
Pointy

Reputation: 413702

The mistake is that you're trying to set "click" behavior by changing the "href" in the first place. Don't do that. Instead, give the <a> tag a "click" handler, and set the "href" to "#" if you don't want the link to "go' anywhere.

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

HREF should only be used for actual URLs. It is considered bad form to use "href="javascript:...".

An action calling JavaScript should go into the onclick attribute.

Upvotes: 0

Dustin Laine
Dustin Laine

Reputation: 38503

<a href="#" onclick="javascript:DoSomething(" + messageID + "); return false;">Link</a>

I add the return false; to prevent the normal behavior of the a.

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630349

Give it an onclick event handler instead, like this:

a.onclick = function() { DoSomething(messageID); };

Leave the href as # and either stop propgation or return false to stop the scroll, for example:

a.onclick = function() { DoSomething(messageID); return false; };

Upvotes: 4

jrn.ak
jrn.ak

Reputation: 36619

You should use the onclick event:

<a href="#" onclick="DoSomething(messageID);">Link Text</a>

Upvotes: 0

Related Questions