carillonator
carillonator

Reputation: 4743

jQuery Mobile Navbar: get active tab

I have a jQuery Mobile Navbar with two tabs:

<div data-role="navbar">
  <ul>
    <li><a href="#" class="tab ui-btn-active">Inbound</a></li>
    <li><a href="#" class="tab">Outbound</a></li>
  </ul>
</div>

When a tab is clicked, I want to

According to the documentation, the active tab has class ui-btn-active, so I listen for clicks and see if that class is present on the clicked button:

$('.tab').click(function() {

  if ( $(this).hasClass('ui-btn-active') ) {
    // already active, do nothing
    console.log("already active");
  } else {
    // newly active, do something
    console.log("newly active");
  }
});

This has worked perfectly for months, but I see now that it is entirely dependent on the timing of when the active class is removed from one and added to the other, relative to when the if is evaluated. Now, after some unrelated code changes, it works as before on desktop browsers, but on mobile browsers, I only get already active, regardless of which button is clicked — i.e. the if happens too late.

What is the smartest way to do this? Can someone explain the sequence of events, and how the inconsistent ordering of events can happen? Is click the right listener to be using for touchscreen devices?

EDIT:

I tried listening for the bubbled event on the parent using .on() and inspecting the event object, hoping the class list it contains would be more accurate, but the behavior is the same:

$('ul').on('click','a',function(event) {
  alert(event.currentTarget.classList.contains('ui-btn-active'));
});

clicking on the inactive tab returns false on desktop browsers, as hoped, and true on mobile browsers.

Upvotes: 1

Views: 4926

Answers (3)

elifares
elifares

Reputation: 1

click has a 300ms delay. Try using "tap" instead of "click"

Upvotes: 0

calanor
calanor

Reputation: 1

I have the same problem, I solved this way:

$("#myselector").on('click','a',function(event) {

   $("#myselector").find('a').each(function(i) { 
     $(this).removeClass('ui-btn-active');
   });
   $(this).addClass('ui-btn-active');

   //  call to my function

});

Upvotes: 0

peterm
peterm

Reputation: 92785

IMHO click is perfectly fine for this purpose and you can simply use a variable to track the active tab. Here is jsFiddle

Upvotes: 1

Related Questions