muttley91
muttley91

Reputation: 12674

jQuery toggle() Bug

I have a page that is set up using a tab interface. When a tab is clicked, the following function is called:

function DisplayContent(tabname, newobject) //for displaying the content in the tabs
{
    document.getElementById("display").innerHTML = document.getElementById(tabname).innerHTML; //writing from a hidden div on the same page
    if(!newobject) newobject=document.getElementById('tab'+tabname);
    if(lastobject) lastobject.className='';
    newobject.className='selected';
    lastobject=newobject;
}

I am using the following function within a button in order to toggle certain elements on the page:

onclick="$('.duedate').toggle();"

If I don't click the button at all, everything is fine. However, if I click the button to show the hidden content, and then re-hide the content, problems ensue when I change tabs - the content goes back to shown when I return to that tab again. Why do these elements appear again, even though I haven't clicked the button? Hopefully I've made some sense, it's a difficult problem to describe.

Upvotes: 0

Views: 605

Answers (1)

gilly3
gilly3

Reputation: 91497

Because you are removing the hidden elements from the dom and replacing them with new HTML. If you want to retain the styles, you have to also retain the elements. Use .show() and .hide() to display your divs, rather than copying the html.

function DisplayContent(tabname, newobject) //for displaying the content in the tabs
{
    $("tabContent").hide();  // hide all the tab content divs
    $("#" + tabname).show(); // show just the current tab's content div 
    if(!newobject) newobject=document.getElementById('tab'+tabname);
    if(lastobject) lastobject.className='';
    newobject.className='selected';
    lastobject=newobject;
}

For this to work, give all of your content divs a class of "tabContent", and put them right after your <div id="display"></div>.

Upvotes: 3

Related Questions