How to get id of pug mixin into a javascript function with inline onclick

Viewed 308

I am trying to make a mixin where multiple counters can be added with different element ids. I have tried a number of things and the closest working example I got is this.


mixin counter(count, id)
  h2(id=id)= count
  button(onclick="addId(1, this.textContent)")= id
  button(onclick ="addId(-1, this.textContent)")= id
  script.
    function addId(x,y){
      let element = document.getElementById(y);
      let content = element.textContent;
      element.textContent = Number(content) + x;
    }

Then I add the mixins using

+counter(0, 'idToAdd')

This works but the issue is the buttons values have to be the id value passed in. I want the one button to be Add and the other Subtract. But everything I have tried has failed. Only by using

this.textContent 

on the button am I able to pass the id in and then it works. So what I want to do is pass the id of the display element into the inline onclick without using this.textContent so I can name the buttons appropriately.

I have tried

#{id}

and

!{id}

and even

`${id}`

But nothing seems to work.

Please help.

Thank you

1 Answers

Instead of creating a new function for each counter, it's better to create a single function that works for all counters. You can directly set the specific ID as a parameter of the function call in the onclick attribute using template string interpolation:

mixin counter(count, id)
  h2(id= id) #{count}
  button(onclick=`updateCounter(1, '${id}')`) Add 1
  button(onclick=`updateCounter(-1, '${id}')`) Subtract 1

+counter(0, 'foo')
+counter(0, 'bar')

script.
  function updateCounter(by, id) {
    let element = document.getElementById(id);
    let currentCount = parseInt(element.textContent, 10);
    element.textContent = currentCount + by;
  }

Compiles to:

<h2 id="foo">0</h2>
<button onclick="updateCounter(1, 'foo')">Add 1</button>
<button onclick="updateCounter(-1, 'foo')">Subtract 1</button>
<h2 id="bar">0</h2>
<button onclick="updateCounter(1, 'bar')">Add 1</button>
<button onclick="updateCounter(-1, 'bar')">Subtract 1</button>
<script>
  function updateCounter(by, id) {
    let element = document.getElementById(id);
    let currentCount = parseInt(element.textContent, 10);
    element.textContent = currentCount + by;
  }
</script>

Related