How to addeventlistener to multiple elements in a single line





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







29















Example 1



Element1.addEventListener ("input", function() {
this function does stuff
});


Example 2



Element1 && Element2.addEventListener("input", function() {
this function does stuff
});


it might not be correct grammatically, but is there a way i can give two elements the same Dom method at the same time (same line) instead of having to write them apart?










share|improve this question




















  • 1





    Possible duplicate of Adding event listeners to multiple elements

    – Meghdad Hadidi
    Dec 4 '16 at 8:22











  • What if you store it inside array then use each function

    – RizkiDPrast
    Dec 4 '16 at 8:23


















29















Example 1



Element1.addEventListener ("input", function() {
this function does stuff
});


Example 2



Element1 && Element2.addEventListener("input", function() {
this function does stuff
});


it might not be correct grammatically, but is there a way i can give two elements the same Dom method at the same time (same line) instead of having to write them apart?










share|improve this question




















  • 1





    Possible duplicate of Adding event listeners to multiple elements

    – Meghdad Hadidi
    Dec 4 '16 at 8:22











  • What if you store it inside array then use each function

    – RizkiDPrast
    Dec 4 '16 at 8:23














29












29








29


8






Example 1



Element1.addEventListener ("input", function() {
this function does stuff
});


Example 2



Element1 && Element2.addEventListener("input", function() {
this function does stuff
});


it might not be correct grammatically, but is there a way i can give two elements the same Dom method at the same time (same line) instead of having to write them apart?










share|improve this question
















Example 1



Element1.addEventListener ("input", function() {
this function does stuff
});


Example 2



Element1 && Element2.addEventListener("input", function() {
this function does stuff
});


it might not be correct grammatically, but is there a way i can give two elements the same Dom method at the same time (same line) instead of having to write them apart?







javascript dom methods






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 4 '16 at 8:27







Jamisco

















asked Dec 4 '16 at 8:13









JamiscoJamisco

3591612




3591612








  • 1





    Possible duplicate of Adding event listeners to multiple elements

    – Meghdad Hadidi
    Dec 4 '16 at 8:22











  • What if you store it inside array then use each function

    – RizkiDPrast
    Dec 4 '16 at 8:23














  • 1





    Possible duplicate of Adding event listeners to multiple elements

    – Meghdad Hadidi
    Dec 4 '16 at 8:22











  • What if you store it inside array then use each function

    – RizkiDPrast
    Dec 4 '16 at 8:23








1




1





Possible duplicate of Adding event listeners to multiple elements

– Meghdad Hadidi
Dec 4 '16 at 8:22





Possible duplicate of Adding event listeners to multiple elements

– Meghdad Hadidi
Dec 4 '16 at 8:22













What if you store it inside array then use each function

– RizkiDPrast
Dec 4 '16 at 8:23





What if you store it inside array then use each function

– RizkiDPrast
Dec 4 '16 at 8:23












6 Answers
6






active

oldest

votes


















53














Well, if you have an array with the elements you could do:



let elementsArray = document.querySelectorAll("whatever");

elementsArray.forEach(function(elem) {
elem.addEventListener("input", function() {
//this function does stuff
});
});





share|improve this answer





















  • 2





    oh, i was hoping it could be done in a single line. Nevertheless i appreciate the answer

    – Jamisco
    Dec 4 '16 at 8:31






  • 5





    If you use ES6 then it's possible: elementsArray.forEach(el => el.addEventListener('input', functionThatDoesStuff))

    – GMaiolo
    Dec 4 '16 at 8:34








  • 11





    What is your definition of "single line"? Any JS program can be written on a single line by removing line breaks.

    – user663031
    Dec 4 '16 at 8:49






  • 1





    You can't get a list with document.getElementsByTagName() eh? I tried that and it didn't work - I had to use querySelectorAll. Thanks though for this, it worked for me!

    – BruceWayne
    Nov 12 '17 at 21:05











  • This doesn't work for me... I got elements in array and I have attached "Click" listener on each element but when I click it event never fires!

    – IamCavic
    Jan 2 '18 at 23:09



















10














Event Bubbling is the important concept in javascript, so if you can add event on DOM directly, you can save some lines of code, no need for looping :



document.addEventListener('click', function(e){
if(e.target.tagName=="BUTTON"){
alert('BUTTON CLICKED');
}
})





share|improve this answer































    4














    I cannot claim credit for this solution but I found a great solution here.



    https://www.kirupa.com/html5/handling_events_for_many_elements.htm



        var theParent = document.querySelector("#theDude");
    theParent.addEventListener("click", doSomething, false);

    function doSomething(e) {
    if (e.target !== e.currentTarget) {
    var clickedItem = e.target.id;
    alert("Hello " + clickedItem);
    }
    e.stopPropagation();
    }





    share|improve this answer































      3














      If you don't want to have a separate elementsArray variable defined you could just call forEach from an unnamed array with the two elements.



      [ Element1, Element2 ].forEach(function(element) {
      element.addEventListener("input", function() {
      this function does stuff
      });
      });





      share|improve this answer































        1














        The easiest way so far I've learned.



        // Get an array of buttons from the page
        var buttons = document.querySelectorAll(".btns");

        // Loop through the resulting array
        for(var i = 0; i < buttons.length; i++){
        buttons[i].addEventListener("click", function() {
        console.log("Hello World");
        });
        }





        share|improve this answer

































          0














          Example for initializing one unique event listener specific to each element.



          You can use the slider to show the values in realtime, or check the console.



          On the <input> element I have a attr tag called data-whatever. You can use that to customize each event listener further.






          sliders = document.querySelectorAll("input");
          sliders.forEach(item=> {
          item.addEventListener('input', (e) => {
          console.log(`${item.getAttribute("data-whatever")} is this value: ${e.target.value}`);
          item.nextElementSibling.textContent = e.target.value;
          });
          })

          .wrapper {
          display: flex;
          }
          span {
          padding-right: 30px;
          margin-left: 5px;
          }
          * {
          font-size: 12px
          }

          <div class="wrapper">
          <input type="range" min="1" data-whatever="size" max="800" value="50" id="sliderSize">
          <em>50</em>
          <span>Size</span>
          <br>
          <input type="range" min="1" data-whatever="OriginY" max="800" value="50" id="sliderOriginY">
          <em>50</em>
          <span>OriginY</span>
          <br>
          <input type="range" min="1" data-whatever="OriginX" max="800" value="50" id="sliderOriginX">
          <em>50</em>
          <span>OriginX</span>
          </div>








          share|improve this answer


























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40956717%2fhow-to-addeventlistener-to-multiple-elements-in-a-single-line%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            6 Answers
            6






            active

            oldest

            votes








            6 Answers
            6






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            53














            Well, if you have an array with the elements you could do:



            let elementsArray = document.querySelectorAll("whatever");

            elementsArray.forEach(function(elem) {
            elem.addEventListener("input", function() {
            //this function does stuff
            });
            });





            share|improve this answer





















            • 2





              oh, i was hoping it could be done in a single line. Nevertheless i appreciate the answer

              – Jamisco
              Dec 4 '16 at 8:31






            • 5





              If you use ES6 then it's possible: elementsArray.forEach(el => el.addEventListener('input', functionThatDoesStuff))

              – GMaiolo
              Dec 4 '16 at 8:34








            • 11





              What is your definition of "single line"? Any JS program can be written on a single line by removing line breaks.

              – user663031
              Dec 4 '16 at 8:49






            • 1





              You can't get a list with document.getElementsByTagName() eh? I tried that and it didn't work - I had to use querySelectorAll. Thanks though for this, it worked for me!

              – BruceWayne
              Nov 12 '17 at 21:05











            • This doesn't work for me... I got elements in array and I have attached "Click" listener on each element but when I click it event never fires!

              – IamCavic
              Jan 2 '18 at 23:09
















            53














            Well, if you have an array with the elements you could do:



            let elementsArray = document.querySelectorAll("whatever");

            elementsArray.forEach(function(elem) {
            elem.addEventListener("input", function() {
            //this function does stuff
            });
            });





            share|improve this answer





















            • 2





              oh, i was hoping it could be done in a single line. Nevertheless i appreciate the answer

              – Jamisco
              Dec 4 '16 at 8:31






            • 5





              If you use ES6 then it's possible: elementsArray.forEach(el => el.addEventListener('input', functionThatDoesStuff))

              – GMaiolo
              Dec 4 '16 at 8:34








            • 11





              What is your definition of "single line"? Any JS program can be written on a single line by removing line breaks.

              – user663031
              Dec 4 '16 at 8:49






            • 1





              You can't get a list with document.getElementsByTagName() eh? I tried that and it didn't work - I had to use querySelectorAll. Thanks though for this, it worked for me!

              – BruceWayne
              Nov 12 '17 at 21:05











            • This doesn't work for me... I got elements in array and I have attached "Click" listener on each element but when I click it event never fires!

              – IamCavic
              Jan 2 '18 at 23:09














            53












            53








            53







            Well, if you have an array with the elements you could do:



            let elementsArray = document.querySelectorAll("whatever");

            elementsArray.forEach(function(elem) {
            elem.addEventListener("input", function() {
            //this function does stuff
            });
            });





            share|improve this answer















            Well, if you have an array with the elements you could do:



            let elementsArray = document.querySelectorAll("whatever");

            elementsArray.forEach(function(elem) {
            elem.addEventListener("input", function() {
            //this function does stuff
            });
            });






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Feb 28 at 16:41

























            answered Dec 4 '16 at 8:28









            GMaioloGMaiolo

            1,8931024




            1,8931024








            • 2





              oh, i was hoping it could be done in a single line. Nevertheless i appreciate the answer

              – Jamisco
              Dec 4 '16 at 8:31






            • 5





              If you use ES6 then it's possible: elementsArray.forEach(el => el.addEventListener('input', functionThatDoesStuff))

              – GMaiolo
              Dec 4 '16 at 8:34








            • 11





              What is your definition of "single line"? Any JS program can be written on a single line by removing line breaks.

              – user663031
              Dec 4 '16 at 8:49






            • 1





              You can't get a list with document.getElementsByTagName() eh? I tried that and it didn't work - I had to use querySelectorAll. Thanks though for this, it worked for me!

              – BruceWayne
              Nov 12 '17 at 21:05











            • This doesn't work for me... I got elements in array and I have attached "Click" listener on each element but when I click it event never fires!

              – IamCavic
              Jan 2 '18 at 23:09














            • 2





              oh, i was hoping it could be done in a single line. Nevertheless i appreciate the answer

              – Jamisco
              Dec 4 '16 at 8:31






            • 5





              If you use ES6 then it's possible: elementsArray.forEach(el => el.addEventListener('input', functionThatDoesStuff))

              – GMaiolo
              Dec 4 '16 at 8:34








            • 11





              What is your definition of "single line"? Any JS program can be written on a single line by removing line breaks.

              – user663031
              Dec 4 '16 at 8:49






            • 1





              You can't get a list with document.getElementsByTagName() eh? I tried that and it didn't work - I had to use querySelectorAll. Thanks though for this, it worked for me!

              – BruceWayne
              Nov 12 '17 at 21:05











            • This doesn't work for me... I got elements in array and I have attached "Click" listener on each element but when I click it event never fires!

              – IamCavic
              Jan 2 '18 at 23:09








            2




            2





            oh, i was hoping it could be done in a single line. Nevertheless i appreciate the answer

            – Jamisco
            Dec 4 '16 at 8:31





            oh, i was hoping it could be done in a single line. Nevertheless i appreciate the answer

            – Jamisco
            Dec 4 '16 at 8:31




            5




            5





            If you use ES6 then it's possible: elementsArray.forEach(el => el.addEventListener('input', functionThatDoesStuff))

            – GMaiolo
            Dec 4 '16 at 8:34







            If you use ES6 then it's possible: elementsArray.forEach(el => el.addEventListener('input', functionThatDoesStuff))

            – GMaiolo
            Dec 4 '16 at 8:34






            11




            11





            What is your definition of "single line"? Any JS program can be written on a single line by removing line breaks.

            – user663031
            Dec 4 '16 at 8:49





            What is your definition of "single line"? Any JS program can be written on a single line by removing line breaks.

            – user663031
            Dec 4 '16 at 8:49




            1




            1





            You can't get a list with document.getElementsByTagName() eh? I tried that and it didn't work - I had to use querySelectorAll. Thanks though for this, it worked for me!

            – BruceWayne
            Nov 12 '17 at 21:05





            You can't get a list with document.getElementsByTagName() eh? I tried that and it didn't work - I had to use querySelectorAll. Thanks though for this, it worked for me!

            – BruceWayne
            Nov 12 '17 at 21:05













            This doesn't work for me... I got elements in array and I have attached "Click" listener on each element but when I click it event never fires!

            – IamCavic
            Jan 2 '18 at 23:09





            This doesn't work for me... I got elements in array and I have attached "Click" listener on each element but when I click it event never fires!

            – IamCavic
            Jan 2 '18 at 23:09













            10














            Event Bubbling is the important concept in javascript, so if you can add event on DOM directly, you can save some lines of code, no need for looping :



            document.addEventListener('click', function(e){
            if(e.target.tagName=="BUTTON"){
            alert('BUTTON CLICKED');
            }
            })





            share|improve this answer




























              10














              Event Bubbling is the important concept in javascript, so if you can add event on DOM directly, you can save some lines of code, no need for looping :



              document.addEventListener('click', function(e){
              if(e.target.tagName=="BUTTON"){
              alert('BUTTON CLICKED');
              }
              })





              share|improve this answer


























                10












                10








                10







                Event Bubbling is the important concept in javascript, so if you can add event on DOM directly, you can save some lines of code, no need for looping :



                document.addEventListener('click', function(e){
                if(e.target.tagName=="BUTTON"){
                alert('BUTTON CLICKED');
                }
                })





                share|improve this answer













                Event Bubbling is the important concept in javascript, so if you can add event on DOM directly, you can save some lines of code, no need for looping :



                document.addEventListener('click', function(e){
                if(e.target.tagName=="BUTTON"){
                alert('BUTTON CLICKED');
                }
                })






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 10 '18 at 12:14









                Ayush SharmaAyush Sharma

                982817




                982817























                    4














                    I cannot claim credit for this solution but I found a great solution here.



                    https://www.kirupa.com/html5/handling_events_for_many_elements.htm



                        var theParent = document.querySelector("#theDude");
                    theParent.addEventListener("click", doSomething, false);

                    function doSomething(e) {
                    if (e.target !== e.currentTarget) {
                    var clickedItem = e.target.id;
                    alert("Hello " + clickedItem);
                    }
                    e.stopPropagation();
                    }





                    share|improve this answer




























                      4














                      I cannot claim credit for this solution but I found a great solution here.



                      https://www.kirupa.com/html5/handling_events_for_many_elements.htm



                          var theParent = document.querySelector("#theDude");
                      theParent.addEventListener("click", doSomething, false);

                      function doSomething(e) {
                      if (e.target !== e.currentTarget) {
                      var clickedItem = e.target.id;
                      alert("Hello " + clickedItem);
                      }
                      e.stopPropagation();
                      }





                      share|improve this answer


























                        4












                        4








                        4







                        I cannot claim credit for this solution but I found a great solution here.



                        https://www.kirupa.com/html5/handling_events_for_many_elements.htm



                            var theParent = document.querySelector("#theDude");
                        theParent.addEventListener("click", doSomething, false);

                        function doSomething(e) {
                        if (e.target !== e.currentTarget) {
                        var clickedItem = e.target.id;
                        alert("Hello " + clickedItem);
                        }
                        e.stopPropagation();
                        }





                        share|improve this answer













                        I cannot claim credit for this solution but I found a great solution here.



                        https://www.kirupa.com/html5/handling_events_for_many_elements.htm



                            var theParent = document.querySelector("#theDude");
                        theParent.addEventListener("click", doSomething, false);

                        function doSomething(e) {
                        if (e.target !== e.currentTarget) {
                        var clickedItem = e.target.id;
                        alert("Hello " + clickedItem);
                        }
                        e.stopPropagation();
                        }






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Mar 13 '18 at 17:18









                        danielladaniella

                        156313




                        156313























                            3














                            If you don't want to have a separate elementsArray variable defined you could just call forEach from an unnamed array with the two elements.



                            [ Element1, Element2 ].forEach(function(element) {
                            element.addEventListener("input", function() {
                            this function does stuff
                            });
                            });





                            share|improve this answer




























                              3














                              If you don't want to have a separate elementsArray variable defined you could just call forEach from an unnamed array with the two elements.



                              [ Element1, Element2 ].forEach(function(element) {
                              element.addEventListener("input", function() {
                              this function does stuff
                              });
                              });





                              share|improve this answer


























                                3












                                3








                                3







                                If you don't want to have a separate elementsArray variable defined you could just call forEach from an unnamed array with the two elements.



                                [ Element1, Element2 ].forEach(function(element) {
                                element.addEventListener("input", function() {
                                this function does stuff
                                });
                                });





                                share|improve this answer













                                If you don't want to have a separate elementsArray variable defined you could just call forEach from an unnamed array with the two elements.



                                [ Element1, Element2 ].forEach(function(element) {
                                element.addEventListener("input", function() {
                                this function does stuff
                                });
                                });






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Oct 4 '18 at 14:23









                                John AylingJohn Ayling

                                312




                                312























                                    1














                                    The easiest way so far I've learned.



                                    // Get an array of buttons from the page
                                    var buttons = document.querySelectorAll(".btns");

                                    // Loop through the resulting array
                                    for(var i = 0; i < buttons.length; i++){
                                    buttons[i].addEventListener("click", function() {
                                    console.log("Hello World");
                                    });
                                    }





                                    share|improve this answer






























                                      1














                                      The easiest way so far I've learned.



                                      // Get an array of buttons from the page
                                      var buttons = document.querySelectorAll(".btns");

                                      // Loop through the resulting array
                                      for(var i = 0; i < buttons.length; i++){
                                      buttons[i].addEventListener("click", function() {
                                      console.log("Hello World");
                                      });
                                      }





                                      share|improve this answer




























                                        1












                                        1








                                        1







                                        The easiest way so far I've learned.



                                        // Get an array of buttons from the page
                                        var buttons = document.querySelectorAll(".btns");

                                        // Loop through the resulting array
                                        for(var i = 0; i < buttons.length; i++){
                                        buttons[i].addEventListener("click", function() {
                                        console.log("Hello World");
                                        });
                                        }





                                        share|improve this answer















                                        The easiest way so far I've learned.



                                        // Get an array of buttons from the page
                                        var buttons = document.querySelectorAll(".btns");

                                        // Loop through the resulting array
                                        for(var i = 0; i < buttons.length; i++){
                                        buttons[i].addEventListener("click", function() {
                                        console.log("Hello World");
                                        });
                                        }






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Nov 8 '18 at 0:35









                                        brookr

                                        1,231912




                                        1,231912










                                        answered May 23 '18 at 16:39









                                        Aldrin EspinosaAldrin Espinosa

                                        217




                                        217























                                            0














                                            Example for initializing one unique event listener specific to each element.



                                            You can use the slider to show the values in realtime, or check the console.



                                            On the <input> element I have a attr tag called data-whatever. You can use that to customize each event listener further.






                                            sliders = document.querySelectorAll("input");
                                            sliders.forEach(item=> {
                                            item.addEventListener('input', (e) => {
                                            console.log(`${item.getAttribute("data-whatever")} is this value: ${e.target.value}`);
                                            item.nextElementSibling.textContent = e.target.value;
                                            });
                                            })

                                            .wrapper {
                                            display: flex;
                                            }
                                            span {
                                            padding-right: 30px;
                                            margin-left: 5px;
                                            }
                                            * {
                                            font-size: 12px
                                            }

                                            <div class="wrapper">
                                            <input type="range" min="1" data-whatever="size" max="800" value="50" id="sliderSize">
                                            <em>50</em>
                                            <span>Size</span>
                                            <br>
                                            <input type="range" min="1" data-whatever="OriginY" max="800" value="50" id="sliderOriginY">
                                            <em>50</em>
                                            <span>OriginY</span>
                                            <br>
                                            <input type="range" min="1" data-whatever="OriginX" max="800" value="50" id="sliderOriginX">
                                            <em>50</em>
                                            <span>OriginX</span>
                                            </div>








                                            share|improve this answer






























                                              0














                                              Example for initializing one unique event listener specific to each element.



                                              You can use the slider to show the values in realtime, or check the console.



                                              On the <input> element I have a attr tag called data-whatever. You can use that to customize each event listener further.






                                              sliders = document.querySelectorAll("input");
                                              sliders.forEach(item=> {
                                              item.addEventListener('input', (e) => {
                                              console.log(`${item.getAttribute("data-whatever")} is this value: ${e.target.value}`);
                                              item.nextElementSibling.textContent = e.target.value;
                                              });
                                              })

                                              .wrapper {
                                              display: flex;
                                              }
                                              span {
                                              padding-right: 30px;
                                              margin-left: 5px;
                                              }
                                              * {
                                              font-size: 12px
                                              }

                                              <div class="wrapper">
                                              <input type="range" min="1" data-whatever="size" max="800" value="50" id="sliderSize">
                                              <em>50</em>
                                              <span>Size</span>
                                              <br>
                                              <input type="range" min="1" data-whatever="OriginY" max="800" value="50" id="sliderOriginY">
                                              <em>50</em>
                                              <span>OriginY</span>
                                              <br>
                                              <input type="range" min="1" data-whatever="OriginX" max="800" value="50" id="sliderOriginX">
                                              <em>50</em>
                                              <span>OriginX</span>
                                              </div>








                                              share|improve this answer




























                                                0












                                                0








                                                0







                                                Example for initializing one unique event listener specific to each element.



                                                You can use the slider to show the values in realtime, or check the console.



                                                On the <input> element I have a attr tag called data-whatever. You can use that to customize each event listener further.






                                                sliders = document.querySelectorAll("input");
                                                sliders.forEach(item=> {
                                                item.addEventListener('input', (e) => {
                                                console.log(`${item.getAttribute("data-whatever")} is this value: ${e.target.value}`);
                                                item.nextElementSibling.textContent = e.target.value;
                                                });
                                                })

                                                .wrapper {
                                                display: flex;
                                                }
                                                span {
                                                padding-right: 30px;
                                                margin-left: 5px;
                                                }
                                                * {
                                                font-size: 12px
                                                }

                                                <div class="wrapper">
                                                <input type="range" min="1" data-whatever="size" max="800" value="50" id="sliderSize">
                                                <em>50</em>
                                                <span>Size</span>
                                                <br>
                                                <input type="range" min="1" data-whatever="OriginY" max="800" value="50" id="sliderOriginY">
                                                <em>50</em>
                                                <span>OriginY</span>
                                                <br>
                                                <input type="range" min="1" data-whatever="OriginX" max="800" value="50" id="sliderOriginX">
                                                <em>50</em>
                                                <span>OriginX</span>
                                                </div>








                                                share|improve this answer















                                                Example for initializing one unique event listener specific to each element.



                                                You can use the slider to show the values in realtime, or check the console.



                                                On the <input> element I have a attr tag called data-whatever. You can use that to customize each event listener further.






                                                sliders = document.querySelectorAll("input");
                                                sliders.forEach(item=> {
                                                item.addEventListener('input', (e) => {
                                                console.log(`${item.getAttribute("data-whatever")} is this value: ${e.target.value}`);
                                                item.nextElementSibling.textContent = e.target.value;
                                                });
                                                })

                                                .wrapper {
                                                display: flex;
                                                }
                                                span {
                                                padding-right: 30px;
                                                margin-left: 5px;
                                                }
                                                * {
                                                font-size: 12px
                                                }

                                                <div class="wrapper">
                                                <input type="range" min="1" data-whatever="size" max="800" value="50" id="sliderSize">
                                                <em>50</em>
                                                <span>Size</span>
                                                <br>
                                                <input type="range" min="1" data-whatever="OriginY" max="800" value="50" id="sliderOriginY">
                                                <em>50</em>
                                                <span>OriginY</span>
                                                <br>
                                                <input type="range" min="1" data-whatever="OriginX" max="800" value="50" id="sliderOriginX">
                                                <em>50</em>
                                                <span>OriginX</span>
                                                </div>








                                                sliders = document.querySelectorAll("input");
                                                sliders.forEach(item=> {
                                                item.addEventListener('input', (e) => {
                                                console.log(`${item.getAttribute("data-whatever")} is this value: ${e.target.value}`);
                                                item.nextElementSibling.textContent = e.target.value;
                                                });
                                                })

                                                .wrapper {
                                                display: flex;
                                                }
                                                span {
                                                padding-right: 30px;
                                                margin-left: 5px;
                                                }
                                                * {
                                                font-size: 12px
                                                }

                                                <div class="wrapper">
                                                <input type="range" min="1" data-whatever="size" max="800" value="50" id="sliderSize">
                                                <em>50</em>
                                                <span>Size</span>
                                                <br>
                                                <input type="range" min="1" data-whatever="OriginY" max="800" value="50" id="sliderOriginY">
                                                <em>50</em>
                                                <span>OriginY</span>
                                                <br>
                                                <input type="range" min="1" data-whatever="OriginX" max="800" value="50" id="sliderOriginX">
                                                <em>50</em>
                                                <span>OriginX</span>
                                                </div>





                                                sliders = document.querySelectorAll("input");
                                                sliders.forEach(item=> {
                                                item.addEventListener('input', (e) => {
                                                console.log(`${item.getAttribute("data-whatever")} is this value: ${e.target.value}`);
                                                item.nextElementSibling.textContent = e.target.value;
                                                });
                                                })

                                                .wrapper {
                                                display: flex;
                                                }
                                                span {
                                                padding-right: 30px;
                                                margin-left: 5px;
                                                }
                                                * {
                                                font-size: 12px
                                                }

                                                <div class="wrapper">
                                                <input type="range" min="1" data-whatever="size" max="800" value="50" id="sliderSize">
                                                <em>50</em>
                                                <span>Size</span>
                                                <br>
                                                <input type="range" min="1" data-whatever="OriginY" max="800" value="50" id="sliderOriginY">
                                                <em>50</em>
                                                <span>OriginY</span>
                                                <br>
                                                <input type="range" min="1" data-whatever="OriginX" max="800" value="50" id="sliderOriginX">
                                                <em>50</em>
                                                <span>OriginX</span>
                                                </div>






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Nov 29 '18 at 3:29

























                                                answered Nov 29 '18 at 3:23









                                                Vincent TangVincent Tang

                                                81121330




                                                81121330






























                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40956717%2fhow-to-addeventlistener-to-multiple-elements-in-a-single-line%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Lallio

                                                    Futebolista

                                                    Jornalista