views:

43

answers:

2

I've been using the jQuery UI tabs for a bit now and an interesting request has come up. The current tab setup is using the rotation feature. I need to find a way to determine if the tab is shown because of the result of the rotation itself, or because a user physically clicked the tab.

I've wired up all of the standard events, show and select and they fire regardless of the source of the tab change.

Does anyone have any ideas? Basically I'd like to do something additional if the user clicked the tab, but not if the tab changes by itself via the rotation.

If I wire up the click even to the tabs themselves it doesn't seem to get fired at all, I'm assuming because the tabs widget is using that event itself.

Edit: here's the basic code

<script type="text/javascript">
$(document).ready(function(){
    $("#featured").tabs(
        {show: function(e, ui) { console.log(e);} }
    ).tabs("rotate", 5000, false);
});
</script>

The console will show the event (e) whether it is clicked by the user or shown as part of the rotation. Also, the same if I change the event from show: to select:

+1  A: 

From the jQueryUI documentation:

This event is triggered when clicking a tab.

$( ".selector" ).tabs({
   select: function(event, ui) { ... }
});
Zlatev
select: is fired if the tab is clicked by the user or if it's done as part of the rotation and thus isn't sufficient to determine the source
Richard Edwards
what is `event.type` when it's triggered by rotation?
Zlatev
event.type is 'tabsselect' when it's triggered by rotation and the same for a user click and it's 'tabsshow' for both sources for the show: event. I was hoping to use it but there seems to be no differentiation.
Richard Edwards
+1  A: 

If you develop your own rotation logic instead of using the built-in rotate method, then you could set a flag that you can check later. Something like this should work:

var isRotating = false,
    rotationInterval = 5 * 1000, // 5 seconds
    rotationTimerId;

function rotate() {

    var tabsElement = $('#my-tabs'),
        currentIndex = tabsElement.tabs('options', 'selected'),
        maxIndex = tabsElement.tabs('length') - 1,
        nextIndex = currentIndex === maxIndex ? 0 : (currentIndex + 1);

    isRotating = true;
    tabsElement.tabs('select', nextIndex);
    isRotating = false;

}
function startRotation() {

    if (!rotationTimerId) {
        rotationTimerId = window.setInterval(rotate, rotationInterval);
    }

}
function stopRotation() {

    if (rotationTimerId) {
        window.clearInterval(rotationTimerId);
        rotationTimerId = null;
    }

}

$('#my-tabs').tabs({
    select: function() {
        alert(isRotating ? 'this is from the rotation' : 'this is from a user click');
    }
});
startRotation();
Ken Browning