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

175
Visualizações
Cant close div by pressing outside div

I want to show a div on link click and hide if click outside the div. The script is not working.

I cant close side bar by pressing outside the div. Here is my code

           <body>
            <div id="mySidenav" class="sidenav ">
              <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
              <a href="#">ITEM 1</a>
              <a href="#">ITEM 2</a>
              <a href="#">ITEM 3</a>
              <a href="#">ITEM 4</a>
            </div>
    
            <!-- Use any element to open the sidenav -->
            <span onclick="openNav()" style="cursor: pointer; background: green; border: 1px solid black; padding: 5px;">Click me to get the right sidebar.</span>
            <!-- Add all page content inside this div if you want the side nav to push page content to the right (not used if you only want the sidenav to sit on top of the page -->
            <div id="main">
              ... rest of the content ...
            </div>
        </body>

This is my javascript functions :

        <script type="text/javascript">
    
        /* Simple appearence with animation AN-1*/
        function openNav() {
            document.getElementById("mySidenav").style.width = "934px";
            document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
        }
        function closeNav() {
            document.getElementById("mySidenav").style.width = "0";
            document.body.style.backgroundColor = "white";
        }
      $(document).mouseup(function(e){
        var container = $("#mySidenav");
    
        // If the target of the click isn't the container
        if(!container.is(e.target) && container.has(e.target).length === 0){
            container.hide();
        }
    });
       
        /* Simple appearence with animation AN-1*/
        </script>
    
    <!-- container -->
    
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
        </script>
    </body>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Here's an example of how you can use event.stopPropagation(). This will allow you to have your $(document).click() function which will close the sideNav, and also prevent that from happening when someone clicks in the sideNav.

https://api.jquery.com/event.stoppropagation/

$(document).click(function() {
  console.log('doc clicked');
})

$('.sideNav').click(function(e) {
  console.log('box clicked');
  e.stopPropagation();
})
.sideNav {
  width: 200px;
  height: 400px;
  background-color: #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='sideNav'></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

I got your mouseup handler working by changing container.hide() to closeNav().

Here is an example by modifying your code:

function openNav() {
  document.getElementById("sidebar").style.width = "200px";
  document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
}

function closeNav() {
  document.getElementById("sidebar").style.width = "75px";
  document.body.style.backgroundColor = "white";
}

$(document).click(function(e) {
  var container = $("#sidebar");

  // If the target of the click isn't the container
  if (!container.is(e.target) && !container.has(e.target).length) {
    closeNav()
  }
});

closeNav()
#sidebar {
  background-color: #cccccc;
  width: 75px;
  height: 100%;
  position: fixed;
  transition: width 750ms;
}

.content {
  margin-left: 75px;
  display: flex;
  height: 100vh;
}

body {
  margin: 0;
  transition: background-color 750ms;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="sidebar">
  <button onclick="openNav()">Open</button>
  <br/> Your sidebar content here!
</div>
<div class="content">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Volutpat ac tincidunt vitae semper quis lectus nulla at volutpat. Accumsan in nisl nisi scelerisque eu ultrices. Ornare suspendisse
  sed nisi lacus. Massa tempor nec feugiat nisl pretium fusce id velit.
</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