How to call JavaScript function instead of href in HTML

I have a layout in HTML

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

I received a response from the server when I sent the request.

With this layout, I got a response from an AJAX request that sends my code to the server.

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

 javascript:ShowOld(2367,146986,2) 

means a browser thing that links if I want to do it in firebug, which works. Now I want to do this, when someone clicks on the link, the browser tries to call the function already loaded in the DOM, instead of opening them in the browser.

+74
javascript debugging html
Feb 15 '11 at 12:52
source share
6 answers

This syntax should work well, 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 RESPONSE TO BUILDING VALUES

If you pass strings, use single quotes for the parameters of your function

 <a href="javascript:ShowOld('foo', 146986, 'bar');"> 
+163
Feb 15 '11 at 12:56
source share

If you only have a β€œclick event handler,” use <button> instead. Link has a specific semantic meaning.

eg:.

 <button onclick="ShowOld(2367,146986,2)"> <img title="next page" alt="next page" src="/themes/me/img/arrn.png"> </button> 
+9
Feb 15 2018-11-15T00:
source share

Try to make your javascript unobtrusive:

  • you must use the real link in the href attribute
  • and add a listener to the click event to handle ajax
+7
Feb 15 '11 at 12:59
source share
 href="#" onclick="javascript:ShowOld(2367,146986,2) 
+4
Feb 15 '11 at 12:56
source share

I use a little CSS in the span to make it look like a link, for example:

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"); } 
+4
Sep 03 '14 at 16:28
source share

You should also separate javascript from 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:

 return false; 

as this will result in the link not opening in the browser.

+3
Feb 15 2018-11-15T00:
source share



All Articles