0

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?

0

1 Answer 1

2

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>

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.