5

I have the following graphical button on my site:

<a href="#" class="addto_cart_btn">
  <span id="btn_text">Click here to add to cart now</span>             
</a>

I want to run a specific javascript script when clicked (current value #) to run some javascript - the javascript code essentially generates a popup iFrame with additional content in it.

What is the best approach for achieving this?

2
  • Do some research first as a simple google search brought up the following post from this very site. It has the same question and an answer. how to run javascript function when click on image? Thanks Commented Oct 1, 2013 at 11:39
  • You shouldn't be using links as buttons--it violates accessibility principles. Links are for going to other pages, buttons are for triggering actions within a page. Commented May 11, 2024 at 18:48

4 Answers 4

5

try this

<script type="text/javascript">
   window.onload = function() {
      document.getElementById("btn_text").onclick = function() {
         // Do your stuff here
      };
   };
</script>

Or if you can use JQuery

<script type="text/javascript">
   $(document).ready(function() {
      $("#btn_text").click(function(){
         // Do your stuff here
      });
   });
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

+1 As others have said you can use the onclick attribute but this is the best practice way of doing it.
You might want to point out that this needs to go in a script tag.
4

One approach is to add an onclick attribute

   <a href="#" class="addto_cart_btn" onclick="someFunction()">
      <span id="btn_text">Click here to add to cart now</span>             
    </a>

And then the javascript:

function someFunction(){
   //do stuff
}

Comments

0

You should use OnClick attribute

<a href="#" class="addto_cart_btn" onclick="yourFunction();">
  <span id="btn_text">Click here to add to cart now</span>             
</a>

Comments

0

for plain javascript

window.onload = function(){
   document.getElementById('btn_text').onclick = function(){
      // do stuff;
   }
}

for jQuery

jQuery(function($){
   $('#btn_text').on('click', function(){
      // do stuff
   })
})

3 Comments

Oh, sorry but I did't check the other answers. But if you check it you can see it's edited after I post this comment.
:) hmm Reputation score should not matter but Knowledge transfer
Also, this answer uses on.("click") in jQuery instead of .click. I believe the on event is the recommended approac.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.