user4463794
user4463794

Reputation:

jQuery show() hide() on load page

I am trying use function show or hide on load page like this :

     $(window).resize(function(){
         var width = $( window ).width()

         if(width >= 1200) {
             console.log("> 1200")

             $('#acct').attr({
                 'style' : 'display: none;', 
             });

             $("#logout").css('display', 'none');
             $("#dropnav").show();
             $("#icontop").show();
             $('.navbar-default').css("max-height", "50px"); 
             $('#meetus').css("margin-left", "-100px");
         } else {
             $("#acct").show();
             $("#logout").show();
             $("#icontop").hide();
             $("#dropnav").hide();
             $('.navbar-default').css("max-height", "999999px"); 
             $('#meetus').css("margin-left", "-60px"); 
         }
    });

and when i run with fuction resize() the page hide and show the components and work perfetly, but on document ready, ou window load nothing happens :(

Upvotes: 0

Views: 142

Answers (1)

Curtis
Curtis

Reputation: 103358

This is because $(window).resize() isn't called on page load.

Refactor the code into a seperate function:

function resizer(){
      var width = $( window ).width()

      if(width >= 1200) {
          console.log("> 1200")
          $('#acct').attr({
               'style' : 'display: none;', 
          });
          $("#logout").css('display', 'none');
          $("#dropnav").show();
          $("#icontop").show();
          $('.navbar-default').css("max-height", "50px"); 
          $('#meetus').css("margin-left", "-100px");
      }
      else {
          $("#acct").show();
          $("#logout").show();
          $("#icontop").hide();
          $("#dropnav").hide();
          $('.navbar-default').css("max-height", "999999px"); 
          $('#meetus').css("margin-left", "-60px"); 
      }
}

Then call it on resize and ready:

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

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

Upvotes: 2

Related Questions