Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Javascript on Image Click

Tags:

javascript

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?

like image 617
Michael Alexander-Thorn Avatar asked Oct 01 '13 10:10

Michael Alexander-Thorn


People also ask

Can I use onclick on image?

Can an image have an onclick event? An image, content within a div, link text, text within a span tag, form buttons – pretty much any HTML tag with content can have the onclick attribute.

How do you link an image in JavaScript?

Set Src Attribute in JavaScript In JavaScript, get a reference to the image tag using the querySelector() method. Then, assign an image URL to the src attribute of the image element.

Can we add event listener to image?

To handle the load event on images, you use the addEventListener() method of the image elements. You can assign an onload event handler directly using the onload attribute of the <img> element, like this: <img id="logo" src="logo.

What is image () in JavaScript?

Image() The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document. createElement('img') .


2 Answers

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>
like image 94
Gurminder Singh Avatar answered Sep 30 '22 06:09

Gurminder Singh


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
}
like image 38
Alex Avatar answered Sep 30 '22 04:09

Alex