Arizonay
Arizonay

Reputation: 41

Hide all elements except one, And show all elements again

<body>
    <div id="e1">Element X1</div>
    <div id="e2">Element 2X</div>
    <div id="e3">Element X3</div>
    <a href="/" id="e3">Hide</a>
</body>

How can i hide the entire body And only show #e2 when i click on #hide, But if i clicked anywhere else out of #e2 again, the hide effect will stop and return to normal.

Upvotes: 0

Views: 9991

Answers (3)

trincot
trincot

Reputation: 350270

Something like this? NB: make sure to give your hide link a unique ID.

Showing/hiding works well with jQuery show and hide methods, but since you wanted the elements to stay in their place, it is more suitable to use the visibility style attribute:

$('#hide').click(function () {
    // hide all in body except #e2, and #e2's parents.
    $('body *').not($('#e2').parents().addBack()).css({visibility: 'hidden'});
    return false; // cancel bubbling and default hyperlink effect.
});

$('#e2').click(function () { // click on #e2
    return false; // cancel bubbling -- ignore click.
})

$(document).click(function (e) { // click on document
    $('body *').css({visibility: 'visible'}); // show all in body.
});
div { border: 1px solid}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="e1">Element X1</div>
<div id="e2">Element 2X</div>
<div id="e3">Element X3</div>
<a href="/" id="hide">Hide</a>

Be aware that these div elements stretch across horizontally, so a click to the right of the text "Element 2X" will still be on #e2.

Upvotes: 4

Scott Marcus
Scott Marcus

Reputation: 65806

Something like this:

// Get reference to the hyperlink
var hideElem = document.getElementById("e4");

// Set up click event handler for link
hideElem.addEventListener("click", function(e){
  var elems = document.querySelectorAll("body *:not(#e2)");
  
  Array.prototype.slice.call(elems).forEach(function(value){
   value.classList.add("hide");
  });
  e.stopPropagation();
});

// Set up click event handler for document
document.addEventListener("click", function(){
  var elems = document.querySelectorAll("body *");
  
  Array.prototype.slice.call(elems).forEach(function(value){
   value.classList.remove("hide");
  });
  
});
.hide { display:none; }
<div id="e1">Element X1</div>
<div id="e2">Element 2X</div>
<div id="e3">Element X3</div>
<a href="#" id="e4">Hide</a>

Upvotes: 2

Sagar
Sagar

Reputation: 493

$('body').click(function(evt){    
if(!$(evt.target).is('#e2')) {
        //If not e2 is clicked then restore the state back of page by removing a specific class 
 }
});

You will need help of css class .hide {display:none;} and add and remove this class when e2 is clicked and remove this class when body is clicked but not e2 as provided above

Upvotes: 1

Related Questions