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