Reputation: 48983
$("#tab1").click(function(){
loadTab(1);
$('div.HOMEtabdiv ul.HOMEtabs a').removeClass('selected');
$(this).addClass('selected');
});
Would it be possible to make the code above into a function where I could just call it like
tab(TAB NUMBER HERE);
and have it add/remove the correct styles/divs?
The whole code for the script is below
<script type="text/javascript">
// array of pages to load
var pageUrl = new Array();
pageUrl[1] = "page1.php";
pageUrl[2] = "somepage2.php";
pageUrl[3] = "lastpage3.php";
// function to load page into DIV
function loadTab(id) {
if (pageUrl[id].length > 0) {
$("#loading").show();
$.ajax({
url: pageUrl[id],
cache: false,
success: function (message) {
$("#tabcontent").empty().append(message);
$("#loading").hide();
}
});
}
}
$(document).ready(function(){
$("#loading").hide();
$("#tab1").click(function(){
loadTab(1);
$('div.HOMEtabdiv ul.HOMEtabs a').removeClass('selected');
$(this).addClass('selected');
});
$("#tab2").click(function(){
loadTab(2);
$('div.HOMEtabdiv ul.HOMEtabs a').removeClass('selected');
$(this).addClass('selected');
});
$("#tab3").click(function(){
loadTab(3);
$('div.HOMEtabdiv ul.HOMEtabs a').removeClass('selected');
$(this).addClass('selected');
});
});
alert(window.location.hash);
</script>
Upvotes: 1
Views: 159
Reputation: 106412
I would suggest creating a closure that will generate your "tab click function". This way the this
parameter when the event is called will still be the DOM object.
// this function creates an event function for a specified tab number.
function makeTabClick(tabNumber) {
// this function is the actual event handler
return function(e) {
loadTab(tabNumber);
$('div.HOMEtabdiv ul.HOMEtabs a').removeClass('selected');
$(this).addClass('selected');
};
}
$('#tab1').click(makeTabClick(1));
$('#tab2').click(makeTabClick(2));
$('#tab3').click(makeTabClick(3));
Another alternative, a little more "jQuery" way - Create a plugin function that will generate the click handler you want.
$.fn.makeTab = function(tabNumber) {
return this.click(function(e) {
loadTab(tabNumber);
$('div.HOMEtabdiv ul.HOMEtabs a').removeClass('selected');
$(this).addClass('selected');
});
}
$('#tab1').makeTab(1);
$('#tab2').makeTab(2);
$('#tab3').makeTab(3);
Upvotes: 4
Reputation: 41853
function tab(num) {
loadTab(num);
$('div.HOMEtabdiv ul.HOMEtabs a').removeClass('selected');
$(this).addClass('selected');
}
But if this is going to be a click handler of the anchor, then you can do this:
function tab(evt) {
loadTab(num);
$('div.HOMEtabdiv ul.HOMEtabs a').each(function(i) {
if(evt.target != this)
$(this).removeClass('selected');
else
$(this).addClass('selected');
}
}
If #tab1
is a wrapper, then you can still get the wrapper (#tab1
) using this
(the anchor) in the each
. All you have to do is make sure that the click event is placed on all appropriate elements.
Upvotes: 1