Close div by close button click or body click by jQuery

In this code there are two elements, a div which acts like a pop up and a button which is clicked to show the div. This snippet enables you to close div by close button click or body click by jQuery like a popup. Though we usually use modals and other pop ups yet sometimes this code is quite helpful.
Along with a little styling is also done to get a view able layout.

Here is the code to show div like a popup in JQuery.

Let’s see the snippet:

1

2

3

4

5

6

<div id="div-to-toggle"style="display: none;">

<button id="close-btn">X</button>

<h1>Thisisheading</h1>

<p>ThisaParagraph inthe div fordemonstration.</p>

</div>

The div with id=”div-to-toggle” is meant to hide and show. It also has a close button i.e, button with id=”close-btn” which also can be clicked to close/hide the div.

To show the div I used a button with id=”click-to-show” which needs to be clicked. Instead of a button you can use any other element, for example an anchor tag/hyperlink any div or span etc. I have place the button inside a div for styling the code for the button is:

1

2

3

<div class="btn-container">

<button id="click-to-show">Click todisplay popup</button>

</div>

The main part is the script given below.

1

2

3

4

5

6

7

8

9

10

11

12

<script>

$('#click-to-show, #div-to-toggle').click(function(e){

if($(e.target).attr('id')!='close-btn'){

$('#div-to-toggle').show();

event.stopPropagation();

}

});

$('body, #close-btn').click(function(){

$('#div-to-toggle').hide();

event.stopPropagation();

})

</script>

On click of #click-to-show and #div-to-toggle (# denotes id) #div-to-toggle is shown, but if the target of click is #close-btn then it is not shown, instead on click event of #close-btn is called which for both #close-btn and body resulting the hidden # div-to-toggle.