Paulcraey Paulcraey - 2 months ago 7
jQuery Question

How to pass a function argument into the jquery selector

I have a site with several pop up windows. I want to use 1 single function on several elements. It works well in regular JS, but not in jQuery.

In my HTML I have something like:

<button onclick="div_show('contact')">More?</button>


and

<div id="contact" >
blah blah
</div>


This #contact element is hidden by default. So if i click on the button the contact div appears with this JS:

function div_show(id) {
document.getElementById(id).style.display = "block";
}


However, i want to use jquery for the fade effects

function div_show(id) {
$(???).fadeIn();
}


How can i make the function argument to pass into the jquery selector

It works well like this of course :

function div_show(id) {
$(#contact).fadeIn();
}


but works only for 1 element.

Answer

I think what you are looking for is this:

$("#" + id).fadeIn();

For multiple selectors you could do this:

$("#" + id1 + ", #" + id2).fadeIn(); //etc

Also for completeness, this line:

 $(#contact).fadeIn();

should be formatted with quotes:

 $("#contact").fadeIn();
Comments