Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

286
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda