-2

I have this button that opens a modal when it is clicked. I am trying to call the onclick function for the button via javascript instead of using the mouse.

I used the dom to get the element via classname and tried to call the onclick function but i couldn't figure it out.

var elements = document.getElementsByClassName("shopify-buy__btn");
for (i=0; i<elements.length; i++) {
  if (elements[i].onclick) {
    elements[i].onclick(); // Run the "onclick" function.
  } 
}

Here's the website with the button:

https://fantastic-choice-042131.framer.app/

Crelloc
  • 113
  • 1
  • 3
  • 1
    `.onClick()` is an event - it doesn't not create a click, it says "do this when a click happens here" – HolyMoly Jun 10 '23 at 17:09
  • 2
    `elements[i].click();` – Đinh Carabus Jun 10 '23 at 17:09
  • 2
    To solve your issue I'd suggest trying `click()` instead of `onClick()`. However, going a step further, I would suggest you improve your codebase by not using `onclick` attributes in your HTML. Use `addEventListener()` to unobtrusively assign the event handlers in your JS. – Rory McCrossan Jun 10 '23 at 17:10

1 Answers1

2

I belive what you are trying to do is:

var elements = document.getElementsByClassName("shopify-buy__btn");
for (i = 0; i < elements.length; i++) {
    elements[i].click(); // Run the "onclick" function by simulating a click.  
}

Although it is probably not the optimal way to do this. See the comments.