Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant get a function with jquery to work

The following code below works fine:

$("#searchTab").click(function(){
$(".tab").addClass("tabNo");
$(".tab").removeClass("tabYes");
$(this).addClass("tabYes");
$(".content").hide();
$("#searchContent").show();
});

but if I try to organize the code into a function like below it does not work. Only "$(".content").hide();" from the function seem to work. Why is that?

function tabSelect(){
$(".tab").addClass("tabNo");
$(".tab").removeClass("tabYes");
$(this).addClass("tabYes");
$(".content").hide();
}

$("#searchTab").click(function(){
    tabSelect();
    $("#searchContent").show();
});
like image 228
Jukke Avatar asked May 18 '26 10:05

Jukke


1 Answers

The this reference has changed. You'll need to pass it as an argument to tabSelect, or wrap it and use the wrapper. ($(this))

function tabSelect($itemToTab){
$(".tab").addClass("tabNo");
$(".tab").removeClass("tabYes");
$itemToTab.addClass("tabYes");
$(".content").hide();
}

$("#searchTab").click(function(){
    tabSelect($(this));
    $("#searchContent").show();
});
like image 131
Stefan Kendall Avatar answered May 21 '26 06:05

Stefan Kendall