Wojciech Maj
Wojciech Maj

Reputation: 1102

Can't hide element on click for some reason

I have an element on my website, it looks like so:

<div class="nw_help"><div class="nw_help_content">...</div></div>

Easy stuff. Using CSS on nw_help:hover, nw_help_content becomes visible. In order to support touchscreens too, I have written the following:

$(document).ready(function() {
    $('.nw_help').click(function() {
        $(this).find(".nw_help_content").css('visibility', 'visible');
    });
});
$(document).ready(function() {
    $('.nw_help_content').click(function() {
        $(this).css('visibility', 'hidden');
    });
});

The first function works flawlessly, the second one doesn't wanna work at all. I've checked if $('.nw_help_content').css('visibility', 'hidden'); is working in browser's console and it is.

Any ideas?

Thanks so much in advance for your answer.

Edit: Now it hit me: the first function is triggered on clicking nw_help_content as well and it "neutralizes" the second function. But how to prevent it?

Upvotes: 0

Views: 142

Answers (4)

ponysmith
ponysmith

Reputation: 427

As Zenith says, this is due to event bubbling... Another solution is to bind the event only to the outer container and simply check for the visibilty:

$(document).ready(function() {
    $('.nw_help').click(function() {
        var content = $(this).find('.nw_help_content');
        if(content.css('visibility') == 'hidden') {
            content.css('visibility','visible');
        } else {
            content.css('visibility','hidden');
        }
    });
});

Upvotes: 0

raam86
raam86

Reputation: 6871

It is actually working/ Since the divs are nested you are both events fire and the div is hidden and shown on same click. use toggle instead.

 $(document).ready(function() {
        $('.nw_help').click(function() {
            $(this).find(".nw_help_content").toggle();
        });
    });

Check out the fiddle

Upvotes: 0

Robert Waddell
Robert Waddell

Reputation: 854

I suggest staying away from direct CSS rule manipulation on this. Just using jQuery show and hide will provide a more solid/reliable result.

$(document).ready(function() {
    $('.nw_help').click(function() {
        $(this).find('.nw_help_content').show();
    });
});
$(document).ready(function() {
    $('.nw_help_content').click(function() {
        $(this).hide();
    });
});

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

I believe if you have the visibility hidden on page render, the element is never rendered. You'll need event delegation:

$(document).ready(function() {
    $('.nw_help').click(function() {
        $(this).find(".nw_help_content").css('visibility', 'visible');
    });


    $(document).on('click', '.nw_help_content', function() {
        $(this).css('visibility', 'hidden');
    });
});

Also, only one DOM ready statement is needed.

Demo: http://jsfiddle.net/7sM3L/4/

Upvotes: 1

Related Questions