user2756503
user2756503

Reputation:

Opening submenu correctly in jQuery

I'm somewhat new to jQuery, and I try to create a mobile menu with submenus which open on "click" event.

My problem is: There are more elements with the "tile" class that have a submenu, and obviously I only want to display the submenu of that one I actually clicked on (not all of them as it happens now).

I tried this, but it opens the submenu of all ".tile" elements:

$(".tile").on("click", function () {
    $(".tile ul").css("display", "block");
});

How should I correct this to display only the correct ".tile ul"?

Upvotes: 1

Views: 68

Answers (2)

PlantTheIdea
PlantTheIdea

Reputation: 16359

@TusharGupta has a good answer (i upvoted it), so long as you dont have multiple submenus. if you do, then use this:

$(".tile").on("click", function () {
    $(this).children('ul').css({display:'block'});
});

This only opens direct children of the item, rather than all children. Otherwise, the use of .find() is preferred as it is the most performant.

Upvotes: 0

Use this keyword

$(".tile").on("click", function () {
    $(this).find('ul').css("display", "block");
});

or

Use .show()

$(".tile").on("click", function () {
    $(this).find('ul').show();
});

this keyword refers the current element .

Upvotes: 2

Related Questions