2

I have this function:

var ButtonChoice = function(key, type, img, label){
this.key = key;
this.type = type;
this.img = img;
this.label = label;
this.getButton = function(){
 return "<img src='img/" + this.img + "' type='" + this.type + "' id='" + 
         this.key + "' class='ButtonsChoice' description='" + this.label + 
         "' />" 
 };
};

And I need to add click function to this images. My question is how to do that?

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
davidson94
  • 31
  • 5
  • Add it to the DOM first, then with a reference to the `Element` you can invoke `element.addEventListener('click', function () { // do something });` – Matt Jun 29 '17 at 08:54
  • 1
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Liam Jun 29 '17 at 08:58

4 Answers4

2

Instead of creating the image as a HTML string you can just create it dynamically using JavaScript, this will allow you to attach the click event dynamically using onclick.

This is how should be your code:

var ButtonChoice = function(key, type, img, label) {
  this.key = key;
  this.type = type;
  this.img = img;
  this.label = label;
  this.getButton = function() {
    var image = document.createElement("img");
    image.src = "img/" + this.img;
    image.type = this.type;
    image.id = this.key;
    image.className = "ButtonsChoice";
    image.description = this.label;
    image.onclick = function(){
        //Put your code here
    }
    return image;
  };
};

Note:

I don't see why you are using a type attribute for your images, type attribute is generally used with inputs and buttons, please check the MDN HTML attribute reference table for more details.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
0

Just add onclick function to your returned value:

 return "<img src='img/" + this.img + "' type='" + this.type + "' id='" + 
         this.key + "' class='ButtonsChoice' description='" + this.label + 
         "' onclick='yourFunc();' />" 
kleinohad
  • 5,800
  • 2
  • 26
  • 34
-1

Add this event listener to a document.ready() event listener:

$('.ButtonsChoice').click(function(e){
    ... do something ...
});

Of course, this treats all button the same that have that class...

  • This will likely not work. The fact that `ButtonChoice` is a function *implies* it will be called after document ready. So you'd need event delegation. – freedomn-m Jun 29 '17 at 08:58
  • this won't work as the button is dynamically created, you'd need to use on and event delegation – Liam Jun 29 '17 at 08:59
-1

you can do it this way,

<img src="example.gif" onclick="a('hello')">

in the above line inside the img tag add a onclick event which will invoke a function a(value)

Deepak Pandey
  • 618
  • 7
  • 19