Jukke
Jukke

Reputation: 349

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();
});

Upvotes: 3

Views: 107

Answers (2)

user113716
user113716

Reputation: 322592

Change this:

tabSelect();

to this:

tabSelect.call( this );

This manually sets the value of this in the calling context of tabSelect().

function tabSelect(){
    $(".tab").addClass("tabNo").removeClass("tabYes");  // chain these!
    $(this).addClass("tabYes");  // now "this" is the element you're expecting
    $(".content").hide();
}

$("#searchTab").click(function(){
    tabSelect.call( this ); // set "this" in the calling context of "tabSelect"
                            //   to the current value of "this" (the element)
    $("#searchContent").show();
});

Upvotes: 4

Stefan Kendall
Stefan Kendall

Reputation: 67892

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();
});

Upvotes: 7

Related Questions