Alex Hamilton
Alex Hamilton

Reputation: 25

jquery toggle not working within if-else statement

I'm trying to hide/show sections of a page using the following script:

$(function () {
    $('.open').on('click', function () {
        var contentType = $(this).attr('id');
        if (contentType == "all") {
            $('.content-div').show();
        } else if (contentType == "train" || "manual") {
            $('.content-div.' + contentType).show();
            $('.content-div:visible:not(.' + contentType + ')').hide();
        } else if (contentType == "close") {
            $('.content-div').hide();
        } else {
            $('.content-div.' + contentType).toggle();
        }
    });
});

A jsfiddle example is here with html

The issue is with the final line in the else part - this works correctly (show/hide the relevant div(s) with the associated class) when outside the if-else statement but doesn't work in the else section - the div appears the first time a numbered button is clicked, but doesn't disappear on reclicking.

What am I doing wrong? Many thanks.

Upvotes: 1

Views: 145

Answers (1)

rocky
rocky

Reputation: 7696

Replace:

} else if (contentType == "train" || "manual") {

with:

} else if (contentType == "train" || contentType == "manual") {

"manual" is always evaluated as true therefore this whole else-if branch is evaluated as true. See MDN for more details.

Upvotes: 2

Related Questions