Reputation: 295
I want to create a close button for some of my popup DIVs. Each one pf them have a particular ID and my idea is to set the CSS 'display' to 'none', based on the Div ID being closed.
The following example is not working. I'm wondering why...
Java Script
function CloseDiv(element) {
var id = $(element).closest('div').attr('id')
alert(id) // It's returning the correct id
$(id).css("display", "none");
}
Html
<span id='close' onclick='CloseDiv(this)'>x</span>
Upvotes: 1
Views: 1229
Reputation: 2165
Just change
$(id).css("display", "none");
to
$('#' + id).css("display", "none");
or better yet, use
$('#' + id).hide();
Upvotes: 1
Reputation: 25527
You don't need to extract the id and make the div hide. You can have a direct selector and makes the div hide.
function CloseDiv(element) {
$(element).closest('div').hide()
}
.hide()
is equivalent to .css("display", "none");
You can also remove the inline function call with jquery like this,
$(".close").click(function() {
$(this).closest("div").hide();
});
Note that I've used class instead of id selector, in case you have multiple elements
Upvotes: 3