Search code examples
javascriptsnackjs

How to Attach an event listener to ElementsByClassName()


I am using the SnackJS API. And I need to attach an event to each input element (Textbox) with the class name of "qty". I am not able to use the id attribute for this, as it is dynamically generated and unique, and is being used by something else:

<script type="text/javascript">
    snack.ready(function () {
        // Do your work.
        // Attach an event to QTY Textbox elements.
        var listener = snack.listener({
            node: document.getElementsByClassName("qty"),
            event: 'blur'
        }, function () {
            alert("hello, element.");
        });

        listener.detach();
        listener.attach();
    });
</script>

How do I use getElementByClassName?


Solution

  • You can either loop over the NodeList that getElementsByClassName returns (calling snack.listener each time you go around the loop), or delegate the event handler as per the API documentation:

    var params = {
      node: document.body,
      event: 'click',
      delegate: function (node){
        return node.getElementsByClassName('qty')
      }
    }
    snack.listener(params, someFunction);