Lego2012
9/26/2016 - 9:43 PM

Create a simple jQuery Modal Window

Create a simple jQuery Modal Window

$(document).ready(function() {

  //select all the a tag with name equal to modal
  $('a[name=modal]').click(function(e) {
    //Cancel the link behavior
    e.preventDefault();
    //Get the A tag
    var id = $(this).attr('href');

    //Get the window height and width
    var winH = $(window).height();
    var winW = $(window).width();

    //Set the popup window to center
    $(id).css('top',  winH/2-$(id).height()/2);
    $(id).css('left', winW/2-$(id).width()/2);

    //transition effect
    $(id).fadeIn(500);

  });

  //if close button is clicked
  $('.modalwindow .close').click(function (e) {
    //Cancel the link behavior
    e.preventDefault();
    $('.modalwindow').fadeOut(500);
  });

});
<!-- #modal is the id of a DIV defined in the code below -->
<a href="#modal" name="modal">Simple Modal Window</a>

<!-- #customize your modal window here -->
<div id="modal" class="modalwindow">
    <b>Testing of Modal Window</b> |

    <!-- close button is defined as close class -->
    <a href="#" class="close">Close it</a>

</div>
/* Making sure that the modal window is hidden by default and on top of all other elements on the website. */
.modalwindow {
  position:fixed;
  width:440px;
  height:200px;
  display:none;
  z-index:9999;
  padding:20px;
}


/* Customize your modal window here, you can add background image too */
#modal {
  width:500px;
  height:203px;
  background: #dd3333;
}
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>