Super quick and easy Modal message
I hate when junior developers say “Oh noes, i need a modal better download jQueryUI”
Creating a simple modal with at most 10 lines of code is ridicolously easy, so easy that i am able to do myself!
I will show you that you don”t need jQueryUI or another jQuery plugin to use fancy modals wasting only 2 nanoseconds of your precious life!
Obiously i will add some fancy css code, who actually is super ugly but we don”t care right?
- Identify your needs. Modal before loading? Modal after button click? Confirm button? The whole difference is no more than 2 lines of CSS. We”ll take on the Button Click Modal Example.
- Place your modal at the top of your <body> like this:
<body> <div id="modal-background"> <div id="modal"> <!-- Modal Content here --> <p>Lorem ipsum and silly stuff</p> <button id="close">Close</button> </div> </div> <!-- You page goes here --> <button id="open">Open</button> </body>
- Now place some CSS, obviously the style and the placement is up to you, making a nice modal is a must, in my example on the bottom of the page i stole it from Bootstrap.
#modal-background{ display: none; position: absolute; top: 0; bottom: 0; left: 0; right: 0; background: black; background-color: rgba(0, 0, 0, 0.9); progid: alpha(opacity = 90); } #modal{ width: 300px; position: absolute; mobile casino left: 41%; top: 33%; padding: 10px; background: white; }
- Now the javascript, i clearly used jQuery, we always have it at hand. Import jQuery from GoogleCDN with
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Then place your code at the bottom of the page, before the </body>
<script type="text/javascript"> $(function(){ $("#open").click(function(){ $("#open").hide(); $("#modal-background").fadeIn(); }) $("#close").click(function(){ $("#modal-background").fadeOut(function(){ $("#open").show(); }); }) }) </script>
- As you see i had some little animations, the open buttons disappears when you click the modal and the modal has fadeIn and fadeOut instead of show/hide. There was no special reason for doing this.
The modal is now completed. No big deals, no extra css and javascripts, all custom!
Good article. I will be facing many of these issues as well..