Reputation: 1547
I have a page which have tabs and these tabs have content which get loaded on click via ajax. Now each time when the page gets loaded I have to activate common certain functions.
Example
$('#form-modal').submit(function(e){//somecode//});
If I dont do it Certain elements won't work as required.
What am currently doing is including these functions in all the tab contents sent via ajax. The page is not getting refreshed its only that new content is getting loaded for which I am including the common functions in the new content again and again.
If I don't include the functions again. The functions won't work for the new content.
I am here referring to jquery functions which are used to manipulate html events
I don't want to include the scripts everywhere. What should I do so that the functions work through out the tabs without including them every where.
Upvotes: 0
Views: 65
Reputation: 6573
You should bind an event handler to an parent element that is in the page on load.
eg:
<div class="tabscontainer">
<div class="tabs">
<ul>
<li>Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
<li>Tab 3</li>
</ul>
</div>
<div class="cont tab1">
Tab 1 Contents
</div>
</div>
ou could show/hide each .cont.tabX if they already exist - load in new one in via ajax if they don't exist.
THEN:
say you loaded in tab2 with a form with id of #form-modal like so
<div class="tabscontainer">
<div class="tabs">
<ul>
<li>Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
<li>Tab 3</li>
</ul>
</div>
<div class="cont tab1">
Tab 1 Contents
</div>
<div class="cont tab2">
<form id="form-modal" />
</div>
</div>
use this jQuery:
$('.tabscontainer').on('submit','#form-modal', function(e){//somecode//});
if you added another form #form2:
$('.tabscontainer').on('submit','#form2', function(e){//form 2 code//});
thsi allows you to l oad all the js you need on the page - even for elements not yet existing - to catch the relevant event as it bubbles up the dom and apply to the correct element
Upvotes: 1