Can an a href call a javascript function?

I have some mockup in HTML

Can an a href call a javascript function?

I got the response from server when I sent the request.

With this mockup I got as a response of AJAX request that sends my code to server.

Well, everything is fine but when I click on the link the browser wants to open the function as link; meaning after click I see the address bar as

javascript:ShowOld(2367,146986,2)

means browser thing that's url if I want to do this in firebug that's work. Now I want to do that then when anyone clicks the link then the browser tries to call the function already loaded in the DOM instead of trying to open them in browser.

Brett DeWoody

56.9k28 gold badges134 silver badges183 bronze badges

asked Feb 15, 2011 at 12:52

1

That syntax should work OK, but you can try this alternative.


or


UPDATED ANSWER FOR STRING VALUES

If you are passing strings, use single quotes for your function's parameters


answered Feb 15, 2011 at 12:56

Dutchie432Dutchie432

28.3k20 gold badges90 silver badges109 bronze badges

3

If you only have as "click event handler", use a

answered Feb 15, 2011 at 13:03

Can an a href call a javascript function?

Felix KlingFelix Kling

769k171 gold badges1068 silver badges1114 bronze badges

2

Try to make your javascript unobtrusive :

answered Feb 15, 2011 at 12:59

sojusoju

24.7k3 gold badges66 silver badges69 bronze badges

2

I use a little CSS on a span to make it look like a link like so:

CSS:

.link {
    color:blue;
    text-decoration:underline;
    cursor:pointer;
}

HTML:

Click Me

JAVASCRIPT:

function showWindow(url) {
    window.open(url, "_blank", "directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes");
}

answered Sep 3, 2014 at 16:28

tolsen64tolsen64

7631 gold badge8 silver badges19 bronze badges

3

Your should also separate the javascript from the HTML.
HTML:

Can an a href call a javascript function?

javascript:

myLink = document.getElementById('function-click');
myLink.onclick = ShowOld(2367,146986,2);

Just make sure the last line in the ShowOld function is:

return false;

as this will stop the link from opening in the browser.

answered Feb 15, 2011 at 13:02

hellsgatehellsgate

5,6955 gold badges31 silver badges47 bronze badges

1

shwz

3865 silver badges21 bronze badges

answered Feb 15, 2011 at 12:56

3

href is optional for a elements.

It's completely sufficient to use

link text

answered Feb 6, 2020 at 13:21

Colin 't HartColin 't Hart

6,9162 gold badges27 silver badges48 bronze badges

Can we pass function in href?

The anwer is: not possible.

Where do I call JavaScript in HTML?