Jquery Toggle on click of image

- 1 answer

Ad

I am trying to understand how the jquery toggle works. I want to toggle to next anchor with class plr-anchor on click of image with class go_down. The data is populated using maps.

Jquery code:

$('.go_down').on('click',function(e){
    #('.plr-anchor').next('.plr-anchor').toggle()});
}

Code snippet:

{data.map(function(categ) {
return <div>
<a className="plr-anchor" id={categ.short_name}></a>
<img src="/static/img/icon_up.png" className="go_down"/>
</div>}.bind(this)}

There seems to be a problem with the syntax on the Jquery call function. I am newbie with Jquery, any help will be great. Thanks in advance.

Ad

Answer

Ad

You have used # instead of $ inside click handler. Also you need to find exact plr-anchor which is before the clicked image. Right now you are toggling all plr-anchor.

For dynamic elements, use $(document).on(event, selector, function(){}); for binding click handlers. See below code

$(function(){
  $(document).on('click','.go_down',function(e){
     $(this).prev('.plr-anchor').toggle();
  });
});
Ad
source: stackoverflow.com
Ad