JordanBarber JordanBarber - 3 months ago 9
HTML Question

If statement using jQuery ':visible' not returning boolean

I have created a fiddle here https://jsfiddle.net/c2gjh43j/3/. I am using the line

if ( !target.siblings("aside").is(":visible") ) {


to check whether the target's 'aside' sibling is not visible, but it always returns true, even after my javascript has shown the 'aside' element. Because of this my else statement will not run. You can see that clicking on a box in the fiddle will show the hidden element but when it is visible, you should be able to click on the box and hide it. What am I doing wrong?

Answer

Well you mixed your priorities maybe and having so much on your mind, you forgot to add the commands to "else" statement (hide and remove class). I also removed the "show" beneath this line:

$(this.resource).removeClass("active");

I modified your code and I hope this works like you want. The other files are intact, only the js file is modified as follows:

Services = {
    resource: "#resources-grid .resource",
    resourceTrigger: "#resources-grid .resource .full-link",
    description: ".description",
    init: function() {
        $(this.resourceTrigger).click(this.toggleResource.bind(this));
    },

    toggleResource: function(e) {
        $(this.resource).removeClass("active");

        var target = $(e.target);

        if ( !target.siblings("aside").is(":visible") ) {
            console.log("yes");

            // Edit START
            $("aside").hide();
            // Edit END

            target.siblings("aside").show();
            target.parents(".resource").addClass("active");
        } else {
            console.log("no");
            target.siblings("aside").hide();
            target.parents(".resource").removeClass("active");
        }
    },
}
Services.init();

As a side note, try to comment your code with tasks "To-do:" and indent your code.

Hope I helped you !

Edit: Add this:

$("aside").hide();

before

target.siblings("aside").show();
Comments