Fellow Stranger
Fellow Stranger

Reputation: 34013

Pass multiple elements to an each function

function generalShowPopup(click_element, show_elements) {
  click_element.on("click", function(event) {
    show_elements.each(function() {
      $(this).show();
    });
    event.preventDefault();
  });
}

With the above function I intend to show an element when a certain link is clicked.

Calling the function like this (one second argument) works fine:

generalShowPopup($(".popup_link"), $(".popup") );

But how could I pass two elements to the second argument, i.e show two elements when a certain link is clicked?

Upvotes: 0

Views: 83

Answers (2)

PeterKA
PeterKA

Reputation: 24638

Just use a comma, ,, inside the selector string, and there really is no reason to use .each():

generalShowPopup($(".popup_link"), $(".popup,.selecctor2, #selector3") );

No need to use each:

function generalShowPopup(click_element, show_elements) {
    click_element.on("click", function(event) {
        event.preventDefault();
        show_elements.show();
    });
}

A quicker way to write all this is:

$(function() {
    $(".popup_link").on('click', function(event) {
        event.preventDefault();
        $(".popup,.selecctor2, #selector3").show();
    });
});

Upvotes: 2

Chen-Tsu Lin
Chen-Tsu Lin

Reputation: 23224

$(".popup") is a jQuery Collection,

Just use .add() method:

generalShowPopup($(".popup_link"), $(".popup").add(".another") );

Upvotes: 1

Related Questions