3

I want to reduce the code.

function one() {
 console.log("hai");
}

document.getElementById('dealsButton_1').onclick = one;
document.getElementById('dealsButton_2').onclick = one;
//I  want the above 2 lines of code reduced to one.

A single function for on click on 'dealsButton_*' patterned id elements. How can I do this. The elements are dynamically loaded.

kukkuz
  • 41,512
  • 6
  • 59
  • 95

4 Answers4

4

You can use querySelectorAll and the selector [id^=dealsButton_] to add the event listener in a single line - see demo below:

function one() {
 console.log("hai");
}

Array.prototype.forEach.call(
  document.querySelectorAll('[id^=dealsButton_]'), function(e) {
  e.addEventListener('click', one);
});
<div id="dealsButton_1">one</div>
<div id="dealsButton_2">two</div>

If the markup is dynamically loaded you can base it on a static element like this:

function one() {
  console.log("hai");
}

document.addEventListener('click', function(e) {
  if (e.target && /^dealsButton_/.test(e.target.id))
    one();
})

// dynamically add
document.body.innerHTML = `<div id="dealsButton_1">one</div>
<div id="dealsButton_2">two</div>`;
kukkuz
  • 41,512
  • 6
  • 59
  • 95
0

Are you looking for something like this:

function onClick(){
  //single handler
}

$('[id*="dealsbutton_"]').click(onClick)
Santiago Benitez
  • 364
  • 2
  • 12
0

Here is a solution where you can choose ID name as u wish without a specific pattern of name.

<html>
  <body>
    <div id="abc">one</div>
    <div id="def">two</div>

    <script type="text/javascript">
      function one() {
       console.log("hai");
      }

      function addOnclickFunc (func, idArray){
        idArray.forEach(function(element) {
          document.getElementById(element).onclick = func;
        })
      }

      addOnclickFunc(one,["abc","def"])
    </script>
  </body>
</html>
Nolyurn
  • 568
  • 4
  • 17
-1

you use jQuery with regex for this

$.each( $("button[id^='dealsButton_']"), function () {
 $(this).on('click', function(){
  //code here
 })
});

if want to make the function call names dynamically. pass it as data attribute to button element and call it using eval function

<button id="dealButton_1" data-click="one"></button>

$.each( $("button[id^='dealsButton_']"), function () {
 $(this).on('click', function(){
   var function_call = $(this).attr('data-click')
   eval(function_call)
 })
});
abhi nagi
  • 19
  • 3