Search code examples
jquerytwitter-bootstrapanchorhref

Navigating to correct div using href with multiple tabs?


I have a multiple tabs in a page each with different Id's that are created at run time so

<div class="span5" id="@model.Id">

        <ul class="nav nav-tabs">
            <li class="active"><a data-toggle="tab" onclick="$('#@model.Id #review').focus();">Review</a></li>
            <li><a data-toggle="tab" href="#@model.Id #awesomediv1">Web</a></li>
            <li><a data-toggle="tab" href="#@model.Id #awesomediv2">Photos</a></li>
            <li><a data-toggle="tab" href="#@model.Id #awesomediv3">Location</a></li>
            <li><a data-toggle="tab" href="#@model.Id #awesomediv4">Map</a></li>
        </ul>
<div class="tabbable">
            <div class="tab-content">

                <div class="tab-pane active" id="awesomediv1">
                   .....
                </div>
...

currently when I change the tab in any of the tabs only the first tab changes. I want the anchor tag to navigate to the respective div of the outer div. e.g. in jquery something like $('#1 awesomediv1') gives me the correct div I want to navigate to. But this does not seem to be working with href.

the model is coming from asp.net mvc.


Solution

  • I solved it using the following

    function activateCorrectDiv(parent, e) {
            $('.tab-pane').removeClass('active');
            $('#' + parent+ ' #' + e).addClass('active');
        };
    
    <a  data-toggle="tab" onclick="activateCorrectDiv(($(this).closest('div').attr('id')),'awesomediv1')">
    

    the idea was to identify which div needs to be active. then make it active and before that just ensure that everything else is not active. active is a css class btw. The selector is $(#parentid #childid) , notice the space between them.

    This may just be a hack but it works !!