Los alerts es algo muy común y muy útil en todo desarrollo web que se precie. Normalmente los utilizamos para mostrar mensajes desde el navegador. Todos los navegadores cuentan con su estilo por defecto para las ventanas alerts. Muchas veces, necesitamos añadir alers personalizados que concuerden con el diseño del theme de nuestro proyecto. Este tutorial te ayudará crear alerts personalizados para ello.
Estos dos scripts, extraidos de la web Codexworld.com, te ayudarán a crear un alert personalizado. Uno es un script de Javascript llamado cwdialog.js y el otro es una hoja de estilo llamada cwdialog.css. Puedes cambiar el estilo del alert modificando el fichero cwdialog.css. En este tutorial veremos cómo utilizar estos dos scripts y cómo personalizar una ventana de alert. Para desarrollar todo esto se ha utilizado jQuery, CSS y HTML. Es muy simple y fácil de usar.
¿Estás preparado? ¡Pues vamos a ello!
Lo primero que debes incluir es la librerÃa jQuery
<script type="text/javascript" src="jquery.min.js"></script>
Incluye el script cwdialog.js y la hoja de estilo cwdialog.css en la página HTML
<script type="text/javascript" src="cwdialog.js"></script> <link type="text/css" rel="stylesheet" href="cwdialog.css"/>
Botón HTML
Simplemente añade un botón en HTML con un evento onClick. En dicho evento hay que llamar a la función Cwdialog() para utilizar el alert personalizado. Como parámetro de la función, tenemos que pasarle el texto que queremos que se muestre.
<button onClick="CWdialog('Esto es un alert');">Haz clic aquÃ</button>
Archivo cwdialog.js
Este archivo contiene el siguiente código Javascript:
// Global CWdialog variables var $CWdialog = null, $overlay = null, $body = null, $window = null, $cA = null, CWdialogQueue = []; // Add overlay and set opacity for cross-browser compatibility $(function() { $CWdialog = $('<div class="cwdialog">'); $overlay = $('<div class="cwdialog-overlay">'); $body = $('body'); $window = $(window); $body.append( $overlay.css('opacity', '.94') ).append($CWdialog); }); function CWdialog(text, options) { // Restrict blank modals if(text===undefined || !text) { return false; } // Necessary variables var $me = this, $_inner = $('<div class="cwdialog-inner">'), $_buttons = $('<div class="cwdialog-buttons">'), $_input = $('<input type="text">'); // Default settings (edit these to your liking) var settings = { animation: 700, // Animation speed buttons: { confirm: { action: function() { $me.dissapear(); }, // Callback function className: null, // Custom class name(s) id: 'confirm', // Element ID text: 'Ok' // Button text } }, input: false, // input dialog override: true // Override browser navigation while CWdialog is visible }; // Merge settings with options $.extend(settings, options); // Close current CWdialog, exit if(text=='close') { $cA.dissapear(); return; } // If an CWdialog is already open, push it to the queue if($CWdialog.is(':visible')) { CWdialogQueue.push({text: text, options: settings}); return; } // Width adjusting function this.adjustWidth = function() { var window_width = $window.width(), w = "20%", l = "40%"; if(window_width<=800) { w = "90%", l = "5%"; } else if(window_width <= 1400 && window_width > 800) { w = "70%", l = "15%"; } else if(window_width <= 1800 && window_width > 1400) { w = "50%", l = "25%"; } else if(window_width <= 2200 && window_width > 1800) { w = "30%", l = "35%"; } $CWdialog.css('width', w).css('left', l); }; // Close function this.dissapear = function() { $CWdialog.animate({ top: '-100%' }, settings.animation, function() { $overlay.fadeOut(300); $CWdialog.hide(); // Unbind window listeners $window.unbind("beforeunload"); $window.unbind("keydown"); // If in queue, run it if(CWdialogQueue[0]) { CWdialog(CWdialogQueue[0].text, CWdialogQueue[0].options); CWdialogQueue.splice(0,1); } }); return; }; // Keypress function this.keyPress = function() { $window.bind('keydown', function(e) { // Close if the ESC key is pressed if(e.keyCode===27) { if(settings.buttons.cancel) { $("#cwdialog-btn-" + settings.buttons.cancel.id).trigger('click'); } else { $me.dissapear(); } } else if(e.keyCode===13) { if(settings.buttons.confirm) { $("#cwdialog-btn-" + settings.buttons.confirm.id).trigger('click'); } else { $me.dissapear(); } } }); }; // Add buttons $.each(settings.buttons, function(i, button) { if(button) { // Create button var $_button = $('<button id="cwdialog-btn-' + button.id + '">').append(button.text); // Add custom class names if(button.className) { $_button.addClass(button.className); } // Add to buttons $_buttons.append($_button); // Callback (or close) function $_button.on("click", function() { // Build response object var response = { clicked: button, // Pass back the object of the button that was clicked input: ($_input.val() ? $_input.val() : null) // User inputted text }; button.action( response ); //$me.dissapear(); }); } }); // Disabled browser actions while open if(settings.override) { $window.bind('beforeunload', function(e){ return "An alert requires attention"; }); } // Adjust dimensions based on window $me.adjustWidth(); $window.resize( function() { $me.adjustWidth() } ); // Append elements, show CWdialog $CWdialog.html('').append( $_inner.append('<div class="cwdialog-content">' + text + '</div>') ).append($_buttons); $cA = this; if(settings.input) { $_inner.find('.cwdialog-content').append( $('<div class="cwdialog-input">').append( $_input ) ); } $overlay.fadeIn(300); $CWdialog.show().animate({ top: '20%' }, settings.animation, function() { $me.keyPress(); } ); // Focus on input if(settings.input) { $_input.focus(); } } // end CWdialog();
Archivo cwdialog.js
Este archivo contiene el siguiente código CSS:
.cwdialog-overlay { background-color:#000; display: none; height: 100%; left: 0; position: fixed; top: 0; z-index:9999; width: 100%; opacity: 0.7 !important; } div.cwdialog { background: #fff; border: 1px solid #aaa; box-shadow: 0px 2px 15px rgba(0,0,0,0.2); -mox-box-shadow: 0px 2px 15px rgba(0,0,0,0.2); -webkit-box-shadow: 0px 2px 15px rgba(0,0,0,0.2); color: #111; display: none; font-family: Arial, sans-serif; font-size: 14px; left: 32% !important; max-height: 90%; overflow: hidden; width:40% !important; border-radius:7px; position: fixed; top: -100%; z-index:9999; } div.cwdialog .cwdialog-inner { padding: 20px 20px 30px 20px; font-family: 'Comic Sans MS'; font-size: 16px; color: #156A07; } div.cwdialog .cwdialog-input { margin-top: 10px; padding: 10px 0; } div.cwdialog .cwdialog-input input { border: 1px solid rgba(0,0,0,0.3); border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; box-shadow: inset 0px 0px 5px rgba(0,0,0,0.1); -mox-box-shadow: inset 0px 0px 5px rgba(0,0,0,0.1); -webkit-box-shadow: inset 0px 0px 5px rgba(0,0,0,0.1); display: block; font-size: 13px; margin: 0 auto; padding: 5px 10px; width: 90%; } div.cwdialog .cwdialog-input input:focus { border-color: #01AEF0; outline: none; } div.cwdialog .cwdialog-buttons { border-top: 1px solid #e5e5e5; box-shadow: inset 0px 1px 0px #fff; -moz-box-shadow: inset 0px 1px 0px #fff; -webkit-box-shadow: inset 0px 1px 0px #fff; padding: 20px 20px; text-align: right; } div.cwdialog .cwdialog-buttons button { background-color: #3276b1; border:1px solid #285e8e; border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; cursor: pointer; font-size: 14px; margin: 0 2px; overflow: hidden; border-radius:5px; font-family: 'Comic Sans MS'; padding: 6px 12px; color:#FFF; } div.cwdialog .cwdialog-buttons button.blue { background: #01AEF0; } div.cwdialog .cwdialog-buttons button.red { background: #D23A30; } div.cwdialog .cwdialog-buttons button.blue, div.cwdialog .cwdialog-buttons button.red { color: #fff; text-shadow: 0px -1px 0px rgba(0,0,0,0.4); } div.cwdialog .cwdialog-buttons button:hover { box-shadow: inset 0px 1px 0px rgba(255,255,255,0.5), 0px 1px 3px rgba(0,0,0,0.4); -moz-box-shadow: inset 0px 1px 0px rgba(255,255,255,0.5), 0px 1px 3px rgba(0,0,0,0.4); -webkit-box-shadow: inset 0px 1px 0px rgba(255,255,255,0.5), 0px 1px 3px rgba(0,0,0,0.4); } div.cwdialog .cwdialog-buttons button:active { box-shadow: inset 0px 1px 2px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.8); -moz-box-shadow: inset 0px 1px 2px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.8); -webkit-box-shadow: inset 0px 1px 2px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.8); }
Fuente: codexworld.com