Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

284
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda