-1

I have a header with some links. When the header gets short enough, it goes into mobile view (collapse style).

I want the dropdown to be shown initially, but can be toggled to hide and show again like normal. Basically what I want is: When the page loads/resizes and the navbar goes into mobile, toggle the dropdown so it's visible.

You can toggle a dropdown by doing:

$("#element").dropdown("toggle");

Play around with my example here: https://codepen.io/anon/pen/ZKbJJV

Pete
  • 51,385
  • 23
  • 99
  • 140
MortenMoulder
  • 5,021
  • 6
  • 44
  • 89

1 Answers1

-1

UPDATE:

$(document).ready(function() {
    $(window).resize(function() {
        if($(window).width()<=768) {
            $("#element").removeClass("dropdown-menu");
        }else{
          $("#element").addClass("dropdown-menu");
        }
    });
    if($(window).width()<=768) {
      $("#element").removeClass("dropdown-menu");
    }else{
      $("#element").addClass("dropdown-menu");
    }
});

Now I've tried again with remove and add classes and it works. http://codepen.io/julianschmuckli/pen/ybYzQe

You can do execute the code, after the page was finished loading:

$(document).ready(function() {
   if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
     $("#element").dropdown("toggle");
   }
});

To detect if it is mobile, I copied the snippet from here: What is the best way to detect a mobile device in jQuery?

Or you can also try this version to define it with a specific width of page:

$(document).ready(function() {
    if($(window).width()<=768) {
        $("#element").dropdown("toggle");
    }
});
Community
  • 1
  • 1
Julian Schmuckli
  • 3,032
  • 9
  • 29
  • 56
  • 1) I don't want to do it only on mobile. 2) What happens if I resize? It won't trigger then. 3) What happens if I resize and the dropdown is shown, then I resize again so it toggles again? It will hide it. Sorry, but it's going to take a bit more than just toggling it. – MortenMoulder Apr 18 '17 at 11:00
  • No offense or anything, but are you actually trying? I provided you with a codepen link and what you're doing doesn't work. If you think how this would work, it would run the toggle code for every pixel you're resizing under 768. If you're resizing your window, it would literally toggle it hundreds of times. – MortenMoulder Apr 18 '17 at 11:11
  • @MortenMoulder Again I've updated my answer with the new code. – Julian Schmuckli Apr 18 '17 at 11:21
  • "**I want the dropdown to be shown initially, but can be toggled to hide and show again like normal**" – MortenMoulder Apr 18 '17 at 11:58