Home > Net >  How to stimulate a click() using plain javascript
How to stimulate a click() using plain javascript

Time:11-30

I have a pretty basic code

if(screen.width > 600) {
  document.querySelector('.toggle-sidenav').click();
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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?

Your fast response is appreciated.

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related