user605334
user605334

Reputation:

How to call JavaScript function instead of href in HTML

I have some mockup in HTML

<a href="javascript:ShowOld(2367,146986,2)"><img title="next page" alt="next page" src="/themes/me/img/arrn.png"></a>

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.

Upvotes: 107

Views: 481844

Answers (7)

Colin &#39;t Hart
Colin &#39;t Hart

Reputation: 7729

href is optional for a elements.

It's completely sufficient to use

<a onclick="ShowOld(2367,146986,2)">link text</a>

Upvotes: 0

nico
nico

Reputation: 103

<a href="#" onclick="javascript:ShowOld(2367,146986,2)">

Upvotes: 5

Dutchie432
Dutchie432

Reputation: 29160

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

<a href="javascript:void(0);" onclick="ShowOld(2367,146986,2);">

or

<a href="javascript:ShowOld(2367, 146986, 2);">

UPDATED ANSWER FOR STRING VALUES

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

<a href="javascript:ShowOld('foo', 146986, 'bar');">

Upvotes: 239

tolsen64
tolsen64

Reputation: 999

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:

<span class="link" onclick="javascript:showWindow('url');">Click Me</span>

JAVASCRIPT:

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

Upvotes: 6

Felix Kling
Felix Kling

Reputation: 816610

If you only have as "click event handler", use a <button> instead. A link has a specific semantic meaning.

E.g.:

<button onclick="ShowOld(2367,146986,2)">
    <img title="next page" alt="next page" src="/themes/me/img/arrn.png">
</button>

Upvotes: 12

hellsgate
hellsgate

Reputation: 6005

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

<a href="#" id="function-click"><img title="next page" alt="next page" src="/themes/me/img/arrn.png"></a>

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.

Upvotes: 3

soju
soju

Reputation: 25312

Try to make your javascript unobtrusive :

  • you should use a real link in href attribute
  • and add a listener on click event to handle ajax

Upvotes: 7

Related Questions