Cómo crear una ventana modal simple en jQuery

En este tutorial, voy a compartir con vosotros el cómo crear una ventana modal muy sencilla con jQuery. Me gusta jQuery, hace que todo sea tan simple y tan fácil... Es posible que no sepas lo que es una ventana modal, no te preocupes, te lo explico en pocas palabras. Se trata de ventanas emergentes desarrolladas con Javascript y/o CSS que buscan captar la atención del usuario, con técnicas sutiles, para llevar a cabo alguna acción concreta.

Para este ejemplo utilizaré facebox (inspirado en facebook). Hay otros, como lightbox, thickbox, multibox, litebox... Puedes encontrar en Internet un montón de librerías para este propósito y cada una con sus diferentes características.

Muy bien, vamos a empezar, este ejemplo te mostrará cómo crear una ventana modal que mostrará el contenido de un div #ID.

Codigo HTML

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

<div id="boxes">

	
	<!-- #customize your modal window here -->

	<div id="dialog" class="window">
		<b>Testing of Modal Window</b> | 
		
		<!-- close button is defined as close class -->
		<a href="#" class="close">Close it</a>

	</div>

	
	<!-- Do not remove div#mask, because you'll need it to fill the whole screen -->	
 	<div id="mask"></div>
</div>

Código CSS

/* Z-index of #mask must lower than #boxes .window */
#mask {
  position:absolute;
  z-index:9000;
  background-color:#000;
  display:none;
}
  
#boxes .window {
  position:fixed;
  width:440px;
  height:200px;
  display:none;
  z-index:9999;
  padding:20px;
}


/* Customize your modal window here, you can add background image too */
#boxes #dialog {
  width:375px; 
  height:203px;
}

Javascript

$(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 screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
	
		//Set height and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		
		//transition effect		
		$('#mask').fadeIn(1000);	
		$('#mask').fadeTo("slow",0.8);	
	
		//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(2000); 
	
	});
	
	//if close button is clicked
	$('.window .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		$('#mask, .window').hide();
	});		
	
	//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		$('.window').hide();
	});			
	
});

Es muy sencillo y fácil de entender. Recuerda, para que funcione debes incluir el framework jQuery.

Mostrando la ventana modal con Javascript

Debido a la demanda popular de :), tengo que poner un ejemplo de esto, que luego siempre me preguntáis. El concepto es simple. Metí el script de la ventana modal dentro de una función, para luego ser capaces de llamar a la ventana modal utilizando una función de javascript.

Sí, con esto también serás capaz de cargar la ventana modal cuando se cargue la página.

$(document).ready(function () {
  //id is the ID for the DIV you want to display it as modal window
  launchWindow(id); 
});

Y si quieres cerrar la ventana modal pulsando una tecla, la tecla que quieras, puedes añadir la siguiente función:

$(document).keyup(function(e) {
  if(e.keyCode == 13) {
    $('#mask').hide();
    $('.window').hide();
  }
});

Usar cookies para no mostrarla siempre al usuario

Para ello necesitas dos funciones (createCookie y readCookie). Es funcionamiento es muy sencillo, si la cookie está creada en la sesión del usuario, no mostraremos la ventana modal, pero si por el contrario, no está creada, significa que no ha visto nuestro modal y por lo tanto, tenemos que mostrarlo.

$(document).ready(function() {
//if the cookie hasLaunch is not set, then show the modal window
if (!readCookie('hasLaunch')) {
	//launch it
	launchWindow('#dialog1');		
	//then set the cookie, so next time the modal won't be displaying again.
	createCookie('hasLaunch', 1, 365);
}

});

Recalcular la posición de la ventana modal y la máscara cuando se redimensione la ventana

En la época que estamos, todo debe ser responsive ya que no solo utilizamos el ordenador para navegar por Internet. Utilizamos diversos dispositivos como los smartphones y las tablets. Este código es muy útil para eso, para cuando el usuario redimensione la ventana, no chafe nuestra ventana modal ni la máscara de opacidad.

$(document).ready(function () {
$(window).resize(function () {
 
 		var box = $('#boxes .window');
 
        //Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
      
        //Set height and width to mask to fill up the whole screen
        $('#mask').css({'width':maskWidth,'height':maskHeight});
               
        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();
 
        //Set the popup window to center
        box.css('top',  winH/2 - box.height()/2);
        box.css('left', winW/2 - box.width()/2);
 
});

});

Fuente: queness.com

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP