Search code examples
jqueryhtmlhideparent

Do not hide specific childnodes onclick a parent


I've got the next HTML code:

<div id="main-container">
  <article id="doyou">...</article>
  <article id="theydid">...</article>
  <article id="nieuws">...</article>
  ...
</div>

I'm trying to hide the articles when clicked on the div outside the articles, but not when the articles itself are clicked. Currently I got the following code, but it ain't working:

code:

$("#main-container").click(function(){
        $('article#doyou').not(this).hide();
        $('article#theydid').not(this).hide();
        $('article#nieuws').not(this).hide();
        $('article#stage').not(this).hide();
        $('article#info').not(this).hide();
        $('article#contact').not(this).hide();
        $('article#letop').not(this).hide();
    });

Solution

  • First of all I'd give each article a common class:

    <div id="main-container">
        <article id="doyou" class="article">...</article>
        <article id="theydid" class="article">...</article>
        <article id="nieuws" class="article">...</article>
        ... other articles ...
    </div>
    

    Then in jQuery you can use that class to hide all except the clicked element:

    $(function() {
        $(".article").click(function() {
            hideArticles();
            $(this).show();
        });
    
        $("#main-container").click(function(e) {
            if (e.target.id == "main-container")
                hideArticles();
        });
    });
    
    function hideArticles() {
        $(".article").hide();
    }
    

    As I mentioned in my comment though, there is no mechanism for displaying all the articles again. Once an article has been clicked, all others will not be recoverable.

    You may want to add a 'show articles' button:

    $("#show-articles").click(function() {
        $(".article").show();
    });