DSA Web Specialists
DSA Web Specialists

Reputation: 311

How can I use the (This) to target a class with slideToggle JQuery?

I need to understand how (this) works. I have seen many different cases and instances where it is used, but used differently. I want to target only one div out of several that has the class name. I can't seem to get this to work properly. I've read several answers in Stackoverflow, but still can't seem to target one class using (this). Thanks yet again for helping me.

the js

<script type="text/javascript">
  jQuery(document).ready(function(){
     jQuery('.expandCollapseMenu').click(function(){
      jQuery(this).parent().find('.menu_product_main_container').slideToggle();
    });
  });
</script>

the html

<div class="menu_category_category">
    <h3 class="basic_catolog">Beverages</h3>        
    <div class="toggle_menu">
        <img alt="" style="border: 0px none;" src="/images/icons/collapse_menu_icon_on.png" class="expandCollapseMenu {src: '/images/icons/expand_menu_icon.png'}" />
    </div>
</div>
<div class="menu_product_main_container">
    <p>Menu Item 1</p>
    <p>Menu Item 2</p>
</div>
<div class="menu_category_category">
    <h3 class="basic_catolog">Lunch</h3>
    <div class="toggle_menu">
    <img alt="" style="border: 0px none;" src="/images/icons/collapse_menu_icon_on.png" class="expandCollapseMenu {src: '/images/icons/expand_menu_icon.png'}" />
    </div>
</div>
<div class="menu_product_main_container">
    <p>Lunch Item 1</p>
    <p>Lunch Item 2</p>
</div>

Upvotes: 0

Views: 293

Answers (2)

Charles Jourdan
Charles Jourdan

Reputation: 810

It misses one .parent()

jQuery(this).parent().find('.menu_product_main_container').slideToggle(); with this line you get the <div class="toggle_menu">

So the solution is jQuery(this).parent().parent().find('.menu_product_main_container').slideToggle();

EDIT :

Ok with the indentation we see better the problem. A solution could be put a new div like that

<div>
  <div class="menu_category_category">
    <h3 class="basic_catolog">Beverages</h3>        
    <div class="toggle_menu">
        <img alt="" style="border: 0px none;" src="/images/icons/collapse_menu_icon_on.png" class="expandCollapseMenu {src: '/images/icons/expand_menu_icon.png'}" />
    </div>
  </div>
  <div class="menu_product_main_container">
    <p>Menu Item 1</p>
    <p>Menu Item 2</p>
   </div>
</div>

I have no more idea for your problem without changing the DOM.

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

The value of this depends on the context the code is in.

In the context of an event handler (such as the function passed to .click()), this will refer to the element that triggered the event (otherwise called the event target).

In the context of an iterating function, such as .each(), this will refer to the current element for the iteration.

Upvotes: 1

Related Questions