1

I have this kind of vertical menu :-

Europe
 France
  Paris
 Germany
  Berlin

Asia
 India
  New Delhi
  Lucknow
 Bangladesh
  Dhaka

What I want to achieve is that if I click on Asia only the elements inside asia should open i.e. only the countries in Asia (not the cities right now) and when I click on the country only the cities of that country should open.

My Jquery looks like this :-

$(document).ready(function(){
     $('.country_name').hide();
     $('.city_name').hide();
     $('.continent_name').click(function(){

        $('.country_name').toggle(); 

        $('.city_name').hide();
     });

     $('.country_name').click(function(){

        $('.city_name').toggle();
     });
});

As you can see it toggles all the elements. How do I go about getting the desired result. I did the search on SO and tried few of the answers but it seems they don't work in my case.

Update :-

Here is the html code (it is in haml)

- @destinations.group_by(&:continent).each do |continent, ds_per_continent|
                %ul(class = "continent_name")
                    %li=link_to continent, "#"
                - ds_per_continent.group_by(&:country).each do |country, ds_per_country|
                    %ul(class = "country_name")
                        %li=link_to country, "#"
                    - ds_per_country.each do |destination|
                        %ul(class = "city_name")
                            %li=link_to destination.name, destination_path(destination)

2 Answers 2

3

Use this:

$("li").click(function(event) {
  $(this).children().toggle();
  event.stopPropagation();
});

A Live Example

I would also suggest you try to outsource your tree needs, I prefer dynaTree plugin.

Sign up to request clarification or add additional context in comments.

Comments

1

Inside your click event handler, use the $(this) selector to refer to the clicked element.

$(document).ready(function(){
     $('.country_name').hide();
     $('.city_name').hide();
     $('.continent_name').click(function(){

        $(this).find('.country_name').toggle();

        $('.city_name').hide();
     });

     $('.country_name').click(function(){

        $(this).find('.city_name').toggle();
     });
});

1 Comment

I assumed that your country elements are children of the continent elements. If that's not the case, you have to adjust the selectors. Without the html code it is hard to tell what's wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.