How to pass data to my click listener

I have a button in my html that when clicked, I need it to pass the index attribute value to my click listener:

<button class="btn buy-button js-prevent-cart-listener guys" index="1">Add To Cart</button>

and the listener:

$('.girls').on('click', buyButtonGirlsClickHandler, index);

So that when I run this function, I can access the event value and use it within the function:

function buyButtonClickHandler(evt) {

I dont want to change it to have an 'onclick()' attached to the button. Is this possible and if so how? Obviously the code above is not able to pass the index value, and i have tried numerous times

Answers 1

  • Instead of passing the event handler directly, wrap it inside a new function. Your index data will be passed because it stays in the scope.

    let index = "whatever your index data is";
    $('.girls').on('click', (e, index) => buyButtonGirlsClickHandler(e, index) );

    Note: I'm using ES6 syntax there, may not work on old browsers.

Related Articles