views:

609

answers:

1

I've started using jQuery's UI Tabs, and they work great for the most part, but I've had some issues. When I switch back and forth between tabs, the functionality on some items is lost when I return to that tab. That led me to question whether or not I was structuring it all correctly. Google searches turned up nothing so I decided to ask here.

So the question is: if I have pages that I'm pulling in via Tabs + AJAX, and those new pages have features that I want to use jQuery with, where do I place that jQuery? My structure right now is as follows:

Page with tabs: main_page.php There are two tabs on that page: one that pulls in "page1.php" via AJAX, and one that pulls in "page2.php".

page1 has its own elements that I then use jQuery on. Where does that jQuery code go? Does it go on main_page.php, or on page1.php?

Right now I've been putting it on page1, which I think is correct, but that has created other issues, so I just wanted to double check and see if that was correct.

+1  A: 

please, put all your javascript in a separate .js file. Separate data (html), presentation (css) and behaviours (javascript, flash...). It will ease the maintenance and scaling of your application. Yours and the other people that may one day have to maintain it.

As to your issue: since you switch tabs, the newly loaded content won't have any behaviour attached to it. Why? when you first load your page, and thus load your javascript it will apply only to the current state of the DOM (the html structure if you like). When you click on another tab, you load your content via ajax, so the page won't be refreshed, which means: this new content won't have that javascript applied onto, since it was not available when the javascript got fired up in the first place. So you have 2 options:

  • inject that javascript along with your loaded html (after it) . That's bad practice but it works.
  • you use jquery live() function to bind the events. That's the right choice.

With live(), the behaviours will be attached to the DOM elements at all time.

so instead of

$('#myel').bind('click',dothis());

you do

$('#myel').live('click',dothis());

This way, no matter which tab is being displayed, its content will have the function bound to without you having to reattach it.

pixeline
So you're saying that I should include all the jQuery as a separate JS file but pulled in by the main_page.php, and then make sure all that jQuery uses Live?
exactly : all the elements that are loaded via ajax should use live() instead of bind() (or 'click()' and other shortcuts).
pixeline