views:

44

answers:

2

Sample html markup below

<div class="container answer_comments">
<p class="comment_text">Hey that's not cool.</p>
<p class="comment_attribs">By Anonymous User on 01 Dec</p>
<p class="comment_text">Is that really why?</p>
<p class="comment_attribs">By person on 27 Nov</p>
<p class="close_comments" onclick="close_comments()">Close</p>
</div>

JS function:

function close_comments() {
var comments_wrapper = $(this).closest('.answer_comments');
comments_wrapper.slideUp();
}

.answer_comments will not close. is that because im using $(this) wrong? This div is repeated many times on the page, what would be the best way to achieve what I'm trying to do?

+3  A: 

check what "this" is, it's probably referring to the function itself, not the element

change

<p class="close_comments" onclick="close_comments()">Close</p>

to

<p class="close_comments" onclick="close_comments(this)">Close</p>

and the function to

function close_comments(element) {
  var comments_wrapper = $(element).closest('.answer_comments');
  comments_wrapper.slideUp();
}

and see what happens

Chad
that works, many thanks.
stef
+4  A: 

You're right that you're using this wrong. That would be the right usage if you were binding the event with jQuery:

$('.close_comments').click(function() {
    var comments_wrapper = $(this).closest('.answer_comments');
    comments_wrapper.slideUp();
});

for your current solution, you'd have to do

function close_comments(obj) {
    var comments_wrapper = $(obj).closest('.answer_comments');
    comments_wrapper.slideUp();
}

and

<p class="close_comments" onclick="close_comments(this);">Close</p>
David Hedlund
+1 for showing the *right* way with `bind`ing.
Emil Ivanov