Pete Pete - 3 months ago 21
Javascript Question

Tabs event clicking on active tab

I'm using jquery ui tabs and was wondering if there is an event for when you click on an active tab (or any tab).

I have tried the

activate
and
beforeActive
but these only seem to fire when a non active tab is clicked on (see following code)



$("#tabs").tabs({
beforeActivate: function(event, ui) {
console.log('beforeActivate')
},
activate: function(event, ui) {
console.log('activate')
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<div id="tabs" class="ui-layout-center">
<ul>
<li>
<a href="#tab-1">Tab #1</a>
</li>
<li>
<a href="#tab-2">Tab #1</a>
</li>
</ul>
<div id="tab-container">
<div id="tab-1">
tab 1!
</div>
<div id="tab-2">
tab 2!
</div>
</div>
</div>





What I'm attempting to do is toggle a class on the ul when the active li is clicked. Can this be done using the tabs extra events as I am trying not to to add a separate click event outside the ui methods

Answer

Try this:

$("#tabs")
    .tabs()
    .on("click", '[role="tab"]', function() {
        $(this).closest("ul") // The current UL
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<div id="tabs" class="ui-layout-center">
  <ul>
    <li>
      <a href="#tab-1">Tab #1</a>
    </li>
    <li>
      <a href="#tab-2">Tab #1</a>
    </li>
  </ul>
  <div id="tab-container">
    <div id="tab-1">
      tab 1!
    </div>
    <div id="tab-2">
      tab 2!
    </div>
  </div>
</div>

Comments