PhilBrown
PhilBrown

Reputation: 3009

inline javascript in href

How can you do something like this:

<a href="some javascript statement that isn't a function call;" >myLink</a>

And have the js in the href execute when the link is clicked.

Upvotes: 17

Views: 34058

Answers (4)

Madog
Madog

Reputation: 1

I know this question is old but I had a similar challenge dynamically modifying the href attribute that sends an email when the anchor tag is clicked.

The solution I came up with is this:

$('#mailLink,#loginMailLink,#sbMailLink').click(function () {
    this.setAttribute('href', "mailto:" + sessionStorage.administrator_mail_address + "?subject=CACS GNS Portal - Comments or Request For Access&amp;body=Hi");
});
<a id="loginMailLink" href= "#" style="color:blue">CACS GNS Site Admin.</a>

I hope that helps.

Upvotes: 0

멍개-mung
멍개-mung

Reputation: 480

You can write inline-code in the same way as <a href="javascript:[code]">

This method is also available in other tags.

addition

if you want to Execution when something tag clicking, you can fix with onClick attribute

<a onClick="function()">

Upvotes: 0

pimvdb
pimvdb

Reputation: 154898

<a href="javascript:var hi = 3;" >myLink</a>

Now you can use hi anywhere to get 3.

Upvotes: 18

meder omuraliev
meder omuraliev

Reputation: 186662

Just put the JS code directly in there:

<a href="#" onclick="a=1;b=2; return false;">fsljk</a>

Though, you should not be doing inline scripting. You should unobtrusively attach event handlers.

<a id="lol" href="/blah">fdsj</a>
<script>
document.getElementById('lol').onclick=function() {
/* code */
};
</script>

Upvotes: 19

Related Questions