Sharon
Sharon

Reputation: 37

Change background when clicked

Can somebody help or assist me ?I have been searching and reading but I am nowhere to find answers. I am kinda not into jquery so I need help. I have a drop down menu. What I would like to achieve from that is , when I click the sub menu with sub sub drop down menu it changes background. Now it worked, the background changes, but it applies to its sibling elements which has also a drop down. I would like to change the background of the element which is clicked.

The jquery:

    $('.withsub a').on('click', function () {
    if ($(this).siblings('.tmenu-subs02').is(':visible')) {
        $(this).siblings('.tmenu-subs02').hide();
        $('.withsub').removeClass('clicked');
    } else {
        $(this).siblings('.tmenu-subs02').show();
        $('.withsub').addClass('clicked');
    }
});

please see actual demo

Upvotes: 1

Views: 86

Answers (3)

Milind Anantwar
Milind Anantwar

Reputation: 82231

You are targetting all .withsub elements whereas you need to only target closest .withsub parent element.

You need to use:

$('.withsub a').on('click', function () {
    if ($(this).siblings('.tmenu-subs02').is(':visible')) {
        $(this).siblings('.tmenu-subs02').hide();
        $(this).closest('.withsub').removeClass('clicked');
    } else {
        $(this).siblings('.tmenu-subs02').show();
        $(this).closest('.withsub').addClass('clicked');
    }
});

Working Demo

You can also narrow down your code by using .toggle() and .toggleClass()

$('.withsub a').on('click', function () {
        $(this).siblings().toggle();
        $(this).closest('.withsub').toggleClass('clicked');
});

Demo using toggle and toggleclass

Upvotes: 1

ketan
ketan

Reputation: 19341

You can do like following. Use .children()

$('.withsub').on('click', function () {
        if ($(this).children('.tmenu-subs02').is(':visible')) {
            $(this).children('.tmenu-subs02').hide();
            $(this).removeClass('clicked');
        } else {
            $(this).children('.tmenu-subs02').show();
            $(this).addClass('clicked');
        }
    });

Check Updated Fiddle

Upvotes: 1

tRx
tRx

Reputation: 813

I updated your fiddle:

$('.withsub a').on('click', function () {
    if ($(this).siblings('.tmenu-subs02').is(':visible')) {
        $(this).siblings('.tmenu-subs02').hide();
        $(this).parent().removeClass('clicked');
    } else {
        $(this).siblings('.tmenu-subs02').show();
        $(this).parent().addClass('clicked');
    }
});

Upvotes: 1

Related Questions