HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Twitter Bootstrap collapsing ONLY "phone view" navbar menu on click

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
clickbootstrapviewmenuphonetwittercollapsingonlynavbar

Problem

This is a hard question for me to ask, because I don't really know how to explain it. So, please, bear with me.

Bootstrap menu, as I know, has 2 modes: "desktop" mode "phone/tablet" mode. The desktop mode is anything above 767px width, and the later is anything below or equal (to 767px).

Easy, we copy the navbar example out of Bootstrap's site. And then we can see that the core of the menu looks something like this:


  
    Toggle navigation
    
    
    
  
  Brand


And something like this:


    Link
    Link


As we can see, the collapsing of the menu is set to the button that appears when the "phone/tablet" mode view is open, and that is fine, but the problem starts when we see that the menu doesn't collapse when we click on a link.

So I manage to solve it by adding the following attributes to each of the "a" elements:

data-toggle="collapse" data-target=".navbar-collapse"


Now it looks ugly(er) ... like this:


    Link

    Link


But now, the problem is worst! When we click on a link and we are not on the "phone" view, we can see that the menu kind of collapses and then displays again.

So I see this solution as a workaround (not as a real fix), and to the eye of the developer (in this case.. me) very, very ugly.

So I solved it the next way:

With the project I'm working with, I have implemented the publish and subscribe pattern, which is not from this subject so I won't go into a dip explanation of it, but basically:

This will subscribe a function to a "topic name":

$.Topic(topicName).subscribe(function(){...});


And this will publish a topic to execute the functions(handlers/callbacks) that were subscribed to that topic:

$.Topic(topicName).publish(arguments);


That being said, the code I want to review is the following. Maybe there is already a better way, but this way has worked for me.

I first added an ID to the ul element that holds the links to get an easy access, this way:

 ... 


I s

Solution

Actually, there's sort of a built in way to do this. Just attach a click handler to the links in your .navbar-nav and call the collapse hide method on the navbar-collapse class:

$('.navbar-nav').on('click', 'li a', function() {
  $('.navbar-collapse').collapse('hide');
});


Oh yeah, and you don't have to worry about it when the nav isn't collapsed, so you don't have to listen for the resize event or anything.

Code Snippets

$('.navbar-nav').on('click', 'li a', function() {
  $('.navbar-collapse').collapse('hide');
});

Context

StackExchange Code Review Q#45134, answer score: 3

Revisions (0)

No revisions yet.