-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/

3
  • 1
    .onClick() is an event - it doesn't not create a click, it says "do this when a click happens here" Commented Jun 10, 2023 at 17:09
  • 2
    elements[i].click(); Commented Jun 10, 2023 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. Commented Jun 10, 2023 at 17:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

or see the 13 year old duplicate
thank you guys! I can't believe I was calling the wrong function

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.