Categorías destacadas
programacion php    
Artículo
0
¡votar!

 Crear un plugin para jQuery que cree un Pop Up

Vamos a crear un plugin para jQuery cuya misión será abrir un Pop-up con una cabecera, un botón de cerrar y un espacio donde poder meter algo de texto.

Lo primero de todo es crear las cosas básicas de la aplicación. Estas cosas serán:

  • Enlace a la librería jQuery
  • Propiedades de estilo
  • Un enlace a un archivo javascript donde tendremos nuestro código.

El código correspondiente a esta parte, sería el siguiente:

<html>
<head>
<title>Basic Pop-Up Tutorial</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
<style type="text/css">
*{	margin:0; padding: 0;}
body { background-color: #fff; }
#wrapper { 
margin-left: auto; 
margin-right: auto;
width: 780px; auto; 
margin-top: 10px; 
background-color: #ededed; 
border: 2px #000 solid; 
padding: 10px;
}
</style>
<script type="text/javascript" src="base.js"></script>
</head>
<body>
<div id="wrapper">
<h2>Lorem Ipsum!</h2>
<p>This is a basic lorem ipsum page, eh?</p>
</div>
</body>
</html>

Para crear el plugin para jQuery, empezamos por añadir la firma en nuestro archivo .js.

(function($){
$.popUp = function(){
};
})(jQuery);

Esto ya se podría utilizar utilizando $.popUp();

En nuestro plugin vamos a permitir al usuario del plugin que ponga algunos datos de configuración como será el texto de la cabecera y el texto del cuerpo del popUp.

$.popUp = function(userParameters){
var defaultParameters = {
head: 'Head Section',
body: 'Body Section'
}
var parameters = $.extend({}, defaultParameters, userParameters);
};

Con este código, le estamos diciendo que si el usuario no indica los parámetros, utilizará los que le hemos indicado por defecto.

El siguiente paso que vamos hacer, es la creación de la ventana de PopUp, independiente del CSS utilizado por el usuario. La función será la siguiente.

function buildPopUp(){
//The Pop-Up Body Section
var window = $(document.createElement('div')).css({'position': 'absolute',
'top': '50px',
'left': '50px',
'width': '360px',
'padding': '20px',
'background-color': '#999acd',
'border': '2px #262866 solid'})
.attr('id', 'myPopUp')
.addClass('popUp')
.html(parameters.body);
//The Pop-Up Head Section
var head = $(document.createElement('div')).css({'position':'absolute',
'width': '100%',
'height': '30px',
'background-color': '#262866',
'border': '2px #262866 solid',
'color': '#999acd',
'top': '-32px',
'left': '-2px'})
.attr('id', 'myPopUpHead');
//THe Pop-Up Head Text Section
var headText = $(document.createElement('span')).css({'float':'left'})
.text(parameters.head);
//The Pop-Up Head Close Button Section
var headCloser = $(document.createElement('span')).css({'float':'right',
'cursor':'pointer'})
.text('X')
.click(function(){
$(this).parents('.popUp').remove();
});
//Append the text and the close button to the head section
head.append(headText)
.append(headCloser);
//Append the head section to the window section
window.append(head);
//Append the window section to the 'body' section, thus adding it to the page
$('body').append(window);											
}

En el código podemos ver como hemos creado el Popup por secciones, dándole a cada una de ellas los estilos que hemos querido.

Este código no hará nada, mientras que no se haga una llamada a la función en nuestro plugin. El código quedaría de la siguiente manera.

(function($){
$.popUp = function(userParameters){
var defaultParameters = {
head: 'Head Section',
body: 'Body Section'
}
var parameters = $.extend({}, defaultParameters, userParameters);
function buildPopUp(){
//The Pop-Up Body Section
var window = $(document.createElement('div')).css({'position': 'absolute',
'top': '50px',
'left': '50px',
'width': '360px',
'padding': '20px',
'background-color': '#999acd',
'border': '2px #262866 solid'})
.attr('id', 'myPopUp')
.addClass('popUp')
.html(parameters.body);
//The Pop-Up Head Section
var head = $(document.createElement('div')).css({'position':'absolute',
'width': '100%',
'height': '30px',
'background-color': '#262866',
'border': '2px #262866 solid',
'color': '#999acd',
'top': '-32px',
'left': '-2px'})
.attr('id', 'myPopUpHead');
//THe Pop-Up Head Text Section
var headText = $(document.createElement('span')).css({'float':'left'})
.text(parameters.head);
//The Pop-Up Head Close Button Section
var headCloser = $(document.createElement('span')).css({'float':'right',
'cursor':'pointer'})
.text('X')
.click(function(){
$(this).parents('.popUp').remove();
});
//Append the text and the close button to the head section
head.append(headText)
.append(headCloser);
//Append the head section to the window section
window.append(head);
//Append the window section to the 'body' section, thus adding it to the page
$('body').append(window);											
}
buildPopUp();
};
})(jQuery);
$(document).ready(function(){
$.popUp();
});

El resultado del código debe de ser algo parecido a la imagen que os ponemos a continuación:


El plugin que hemos creado, también se puede utilizar añadiendo algunos valores, ya que si os acordáis, dejamos la posibilidad de que el usuario pudiera poner el texto y cabecera que quieran. Algunos ejemplos podrían ser:

$(document).ready(function(){
//Empty parameters
$.popUp();
//Only body content
$.popUp({
body: '

My PopUp

This is my pop-up!

'; }); //Using both parameters $.popUp({ head: 'Welcome!', body: 'This is my website/page/whatever!' }); //Using only head section $.popUp({ head: 'Useless pop-up!' }); });
Vía: dreamincode
   
Publicado por:
angel carrero
Recomendar
a un amigo
Compartir
en redes
 
Comentarios
 
BBDD
Entornos de desarrollo
Entretenimiento
Herramientas
Internet
Lenguajes de script
Lenguajes imperativos
Lenguajes orientados a objeto
Otros lenguajes
Plataformas
Teoría
Varios
Copyright © 1998-2011 Programación en Castellano. Todos los derechos reservados
Datos legales | Politica de privacidad | Contacte con nosotros | Publicidad

Diseño web y desarrollo web. Un proyecto de los hermanos Carrero.

Red internet:
Juegos gratis | Servidores dedicados
Más internet: Password | Directorio de weblogs | Favicon