Note: Using a 3rd party tab system is not an option so please don’t even recommend that.
On my page, I have several <div>s and several tabs. Each div can belong to multiple tabs. For example, all divs belong to the ‘All’ tab, and then some divs belong to the tab ‘Today’, some to ‘Tomorrow’, etc.
What I want to do is, when the user clicks the Today tab, I want to only show the divs which belong to that tab. When he clicks any other tab, then the previous tab’s divs should get hidden and the selected tab’s divs should show. Pretty standard tabbing behavior so far.
However where this is different is, one div can be shared between multiple tabs.
I was thinking that, whenever a new tab is selected, I could simply loop through all the divs of the last selected tab, hide them, and then loop through the current tab’s divs and show them.
However I’m wondering if there would be any more efficent / less CPU intensive method. Also, this method will cause some divs to be hidden only to then be showered again right away if they’re shared between the last tab and current tab. (For example: div_111 could be shared between Today and Tomorrow. User clicks Today, div_111 is shown. Then he clicks Tomorrow, div_111 is hidden at first, only to then be shown again).
Any suggestions?
The thing you want to watch out for is redraws. When you add or remove an element the browser has to figure out how the change affects every other element on the page, and reposition / resize every element accordingly. This process is almost always the most expensive part of a DOM manipulation – certainly more expensive than figuring out which elements go in which tabs.
Browsers try to optimize redraws – they redraw as little of the page as possible, and sometimes group multiple changes into the same redraw. However, it is best to take matters into your own hands. You can make sure there are no more than two redraws, no matter how many nodes you add or remove, by first removing the parent node from the DOM, then making all your changes, then re-appending it. Here’s a simple example:
Depending on your layout, removing
containermay cause the content below it to momentarily jump up. If you want a polished appearance you can either fix the height ofcontainer‘s parent or insert a placeholder in its place withcontainer.parentNode.replaceNode().If you minimize redraws then you shouldn’t have any efficiency problems. But if you still want to tweak, sure, optimize your content insertion logic. The simplest way to do that would probably be to segregate content that is tied to a single tab from content that shows up in multiple tabs, possibly by using different containers for each content type. Remember that the best solution is the one that is no more generalized than it needs to be.