1

I have a autoclick script which is made with javascript codes. It is working only with ID. Not working with Class. I want to convert it to jQuery and working with class. Please help me..

<a href="https://stackoverflow.com" id="autoclick">Autoclick</a>

<script type="text/javascript">
var autoclickBtn = document.getElementById("autoclick");
autoclickBtn.addEventListener("click", () => {
  console.log("Button clicked");
});
var interval = window.setInterval(() => {
  autoclickBtn.click();
}, 2000);
</script>
Hansika
  • 47
  • 5
  • Possibly relevant: [how to get element by class name](https://stackoverflow.com/questions/17965956/how-to-get-element-by-class-name) – freedomn-m Sep 18 '22 at 10:13
  • The world has been moving away from jQuery for 7 years and you go the opposite direction :) – connexo Sep 18 '22 at 13:50

1 Answers1

1

You just need a jQuery selector and instead of addEventListener(), you may use either click() or on().

$('.autoclick').on("click", () => {
  console.log("Button clicked");
});
window.setInterval(() => {
  $('.autoclick')[0].click();
}, 2000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://stackoverflow.com" class="autoclick">Autoclick</a>
Reza Saadati
  • 5,018
  • 4
  • 27
  • 64