I have some links where I’d like to basically do a class swap. When I have it set up like so it runs all the way through:
$("#work").click(function() {
$(".nav_middle_text").removeClass("selected");
$(".nav_middle_text").addClass("notselected");
$(this).removeClass("notselected");
$(this).addClass("selected");
a1=1;
$("#top_section").animate({
height:30
},450);
$("#bottom_section").animate({
height:$("#grid").outerHeight(true)
}, 450);
$("#about_container").animate({
marginTop:$("#about_container").outerHeight(true) *-1
}, 450);
});
But when I try to set it up this way it runs the first two add and remove classes with the specific class, but the second two using ‘this’ don’t work. Is there a reason running it this way prevents ‘this’ from working?
function nav_click() {
$(".nav_middle_text").removeClass("selected");
$(".nav_middle_text").addClass("notselected");
$(this).removeClass("notselected");
$(this).addClass("selected");
}
$("#work").click(function() {
nav_click();
a1=1;
$("#top_section").animate({
height:30
},450);
$("#bottom_section").animate({
height:$("#grid").outerHeight(true)
}, 450);
$("#about_container").animate({
marginTop:$("#about_container").outerHeight(true) *-1
}, 450);
});
Thanks in advance for any help
When you call the function
nav_click(),thisis no longer what it was inside the click handler. If you want to use thenav_click()function, then you must pass the value ofthisto that function. You can either do that by causingthisto be set appropriately inside the function:Or, you can just pass it as an ordinary argument and change nav_click() to use that argument
FYI, the value of
thisinside a function is determined by how that function is called. If using just a normal function call likenav_click(), thenthisis reset to either thewindowobject (normal JS mode) or toundefined(JS strict mode).To explicitly cause
thisto be set to a particular value inside a function, use.apply()or.call(). See the MDN pages for a description of these methods here and here.