How To Close div by close button click or body click by jQuery

Close div by close button click or body click by jQuery

close div by close button click or body click by jquery, jquery popup

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:

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:

The main part is the script given below.

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.

The complete code is:

 

One thought on “Close div by close button click or body click by jQuery

Leave a Reply