Josh Rodgers
Josh Rodgers

Reputation: 587

Combining Multiple jQuery

I have the following two functions that do the same thing, any way I can combine these two functions into a single function?

$(document).ready(function(){
    $("#nav li").click(function(e) {
        e.preventDefault();
        $("#nav li").removeClass("current_page_item");
        $(this).closest("li").addClass("current_page_item");
    });
    $("#overlay li").click(function(e) {
        e.preventDefault();
        $("#overlay li").removeClass("current_page_item");
        $(this).closest("li").addClass("current_page_item");
    });
});

Thanks,
Josh

Upvotes: 0

Views: 29

Answers (1)

jspcal
jspcal

Reputation: 51894

You could use a pair of selectors combined with a comma. The matching elements for both selectors will be returned:

$("#nav li, #overlay li").click(function(e) {
    e.preventDefault();
    $(this).closest('#nav, #overlay').find('li').removeClass("current_page_item");
    $(this).closest("li").addClass("current_page_item");
});

To deselect the other elements when this is clicked, find the ancestor matching the container ID (nav or overlay), and remove the current_page_item class from the descendant li elements.

Upvotes: 5

Related Questions