2

I have a JS Fiddle, my question is after first click things are working fine, but if again click on H3, the newclass is not getting toggled.

thanks for the help in advance

$('.recommendation-block > h3').addClass('newclass');
$('.recommended-product').addClass('hide');
$(document).ready(function () {
    $('.recommendation-block > h3').click(function () {
        $(this).next('.recommended-product').toggleClass('active');
        if ($('.recommended-product').hasClass('active')) {
            $(this).closest('.recommendation-block > h3').toggleClass('newclass1');
        }
    });
});

2 Answers 2

1

I think you need to use the version of toggleClass which takes a switch param, also you need to target the recommended-product which is in the current context.

$(document).ready(function () {
    $('.recommendation-block > h3').click(function () {
        var $prod = $(this).next('.recommended-product').toggleClass('active');
        $(this).closest('.recommendation-block > h3').toggleClass('newclass1', $prod.hasClass('active'));
    });
});

Demo: Fiddle

In your case, the if block is executed only in alternate clicks because the hasClass will return true only when the active class is added to the recommended-product

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

1 Comment

if i want to keep one option open and another one drop down, the newclass1 toggle is not getting applied, can you kindly help jsfiddle.net/69JG7/4
0
$('.recommendation-block > h3').addClass('newclass');
$('.recommended-product').addClass('hide');
$(document).ready(function(){
    $('.recommendation-block > h3').click(function() {
        $(this).next('.recommended-product').toggleClass('active');
        $(this).toggleClass('newclass1');
    });
});

Comments

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.