Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

279
Views
How to stimulate a click() using plain javascript

I have a pretty basic code:

if(screen.width > 600) {
  document.querySelector('.toggle-sidenav').click();
}

As soon as the screen is > 600px I want to click that div that has a class of toggle-sidenav but the .click() method in Javascript is not working.

I don't want to use jQuery.

How can I achieve this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use dispatchEvent. The example shows here in resizing the screen, the function gets the width which is passed to another function and then dispatchEvent.. Here the function is using the clientWidth to show the working but in your code you can use any other key

const sideNav = document.querySelector('.toggle-sidenav');
sideNav.addEventListener('click', () => {
  alert('Click Triggered')
})
window.addEventListener('resize', (e) => {
  const width = document.body.clientWidth;

  triggerClick(width)
})

function triggerClick(width) {
  if (width > 600) {
    console.log(width)
    sideNav.dispatchEvent(new Event('click'))
  }
}
<div class='toggle-sidenav'>
  Test
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!