user3438917 user3438917 - 6 months ago 16
Javascript Question

How to toggle div from display none to visible

I have a sub-navigation (

.nav-sub-wrapper
) that currently loads hidden and should only display visible when triggered on mobile/tablet devices. I have set the div with
display:none
, but then can't toggle it to visible or
display:block
when on mobile/tablet devices. I have also set the div to load hidden with jQuery, but again can't get the div to toggle visible on mobile/tablet devices.

if($(window).width() == '768'){
$(".nav-sub-wrapper").hide();

$(".hamburger").on('click', function(){
$(".nav-sub-wrapper").toggle();
});
}

Lou Lou
Answer

I see that you use == in your test, did you try to put <= instead. Then you indicate 768 as a string and not a number, try to change that. Also if you test your website on the desktop browser, maybe you could try to put code into a .resize(), like so :

<!doctype html>
<html>
<head>
    <title>test</title>
    <style>
      .nav-sub-wrapper {
        height: 100px;
        width: 100px;
        background-color: blue;
      }

      .hamburger {
        position: absolute;
        top: 0;
        right: 0;
        width: 25px;
        height: 25px;
        background-color: red;
      }
    </style>
</head>
<body>
    <div class="nav-sub-wrapper"></div>
    <div class="hamburger"></div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.js"></script>
    <script>

      function navHidden() {
        if($(window).width() <= 768){
        $(".nav-sub-wrapper").hide();
        $(".hamburger").on('click', function(){
        $(".nav-sub-wrapper").toggle();
        });
       }else{
        $(".nav-sub-wrapper").show();
       }
      }

      $( window ).resize(function() {
       navHidden();
      });

      $( document ).ready(function(){
        navHidden();
      });

    </script>
</body>
</html>

I also added an else condition so the .nav-sub-wrapper displays back over 768px wide. You can try this in your navigator and tell me if it matches what you expected ;-)

Comments