Div as modal - javascript

I need JavaScript that shows a hidden div in the center of the screen as modal with a dark background, like a jquery dialog!

Example:

<div id='divToShow' style='display:none'> Here is the content of the div that should be shown as modal on the center of the page! </div> 

Who can help? Thanks

+1
source share
2 answers

A simple modal popup div or dialog can be done using CSS properties and a bit of jQuery. The basic idea is simple:

1. Create a div with a translucent background and show it on top of your content page by click. 2. Show your pop-up div or warning div on top of the translucent dimming / hiding div.

So we need three divs:

content (the main content of the site). hider (To reduce the content). popup_box (modal div to display).

First, let's define CSS:

  #hider { position:absolute; top: 0%; left: 0%; width:1600px; height:2000px; margin-top: -800px; /*set to a negative number 1/2 of your height*/ margin-left: -500px; /*set to a negative number 1/2 of your width*/ /* z- index must be lower than pop up box */ z-index: 99; background-color:Black; //for transparency opacity:0.6; } #popup_box { position:absolute; top: 50%; left: 50%; width:10em; height:10em; margin-top: -5em; /*set to a negative number 1/2 of your height*/ margin-left: -5em; /*set to a negative number 1/2 of your width*/ border: 1px solid #ccc; border: 2px solid black; z-index:100; } 

It is important that we set our zider index hider index lower than pop_up, since we want to show popup_box on top.
Here comes the java Script:

  $(document).ready(function () { //hide hider and popup_box $("#hider").hide(); $("#popup_box").hide(); //on click show the hider div and the message $("#showpopup").click(function () { $("#hider").fadeIn("slow"); $('#popup_box').fadeIn("slow"); }); //on click hide the message and the $("#buttonClose").click(function () { $("#hider").fadeOut("slow"); $('#popup_box').fadeOut("slow"); }); }); 

And finally, HTML:

 <div id="hider"></div> <div id="popup_box"> Message<br /> <a id="buttonClose">Close</a> </div> <div id="content"> Page main content.<br /> <a id="showpopup">ClickMe</a> </div> 

I used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

+5
source

Here is an example jpiddle modal overlay using jQuery.

http://jsfiddle.net/r77K8/1/

Hope this helps you.

Bean

+1
source

Source: https://habr.com/ru/post/1445608/


All Articles