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

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

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 Denunciar

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