4

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

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Damien
  • 621
  • 1
  • 7
  • 17

1 Answers1

11

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');
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Worth mention, if `.message-head` elements will be created on the fly, It would be good idea to bind event using `document`. – px5x2 Nov 03 '15 at 10:30
  • Works like a charm @Rory thanks. Good job I've got a Javascript course coming up soon as it looks like I'll be getting more to do with the new system – Damien Nov 03 '15 at 10:38
  • @Damien no problem, glad to help – Rory McCrossan Nov 03 '15 at 10:39