Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript to show and hide a message

I've set up a small script to show and hide a div..

$('.message-head').click(function () {
    $('.message-preview').toggle('slow');
});

Works perfectly as it should do. My problem is that I have multiple instances of the html markup on the page, which is inside a foreach loop..

<div class="two-three-col message-head">
    <h4>@message.Subject</h4>
    <div class="message-preview">
        @Html.Raw(@message.Body)
    </div>
</div>

This is basically for a messaging system that has been chopped and changed a lot and has been left to me to fix; not being the best at javascript I'm quite stuck. So how can I modify the js so that if I click on say message 1 then only message 1 will show/hide on click and the rest will stay inactive.

Thanks in advance

like image 624
Damien Avatar asked Dec 18 '22 22:12

Damien


1 Answers

You can use the this keyword to refer to the element which raised the event. From there you can traverse the DOM to find the related .message-preview element. Try this:

$('.message-head').click(function () {
    $(this).find('.message-preview').toggle('slow');
});
like image 89
Rory McCrossan Avatar answered Dec 29 '22 15:12

Rory McCrossan