javascripthtmlonclick

give an onclick function to be executed to every element with a certain class


How would i go about making something like this - i have multiple elements with a certain class and i would like this to happen:

element1 - onclick fires someFunction(13);

element2 - onclick fires someFunction(27);

element3 - onclick fires someFunction(81);

i am loading these elements in dynamically so i can't put it manually into my js file. I also can't give them an onclick as i load them with php. I am looking for a purely js answer so please no jQuery.


Solution

  • The simplest way of doing this is giving the elements a data-attribute with the parameter for the function you want to run:

    <div class="someclass" data-parameter="12">
    <div class="someclass" data-parameter="13">
    <div class="someclass" data-parameter="14">
    

    and then run this:

    function setMyHandler(){
       var elements = document.getElementsByClassName('someclass');
       for(var i = 0; i < elements.length; i++){
          elements[i].onclick = function(){ myFunction(this.data.parameter); };
       }
    }
    

    Here is a link for data attributes: data attributes

    And here is a snipplet to see the simple version of it in action:

    function setMyHandler(){
       var elements = document.getElementsByClassName('someclass');
       for(var i = 0; i < elements.length; i++){
          elements[i].onclick = function(){window.alert(this.dataset.somevalue);};
       }
    }
    
    setMyHandler();
    body {
      display: flex;
      justify-content: center;
    }
    
    div.someclass {
      margin: 2%;
      width: 50px;
      height: 50px;
      border-radius: 50%;
      cursor: pointer;
      background: #80bfff;
      box-shadow: 0px 2px 6px 0px rgba(0,0,0,0.7);
      transition: background 0.3s ease;
    }
    
    div.someclass:hover {
      background: #3399ff;
    }
    <div class="someclass" data-somevalue="13">  </div>
    
    <div class="someclass" data-somevalue="14">  </div>
    
    <div class="someclass" data-somevalue="15">  </div>