Dialogs JQuery: Mensajes de Alerta y Confirm


Buenas :). Estuve buscando cómo modificar el estilo de los mensajes alert y confirm, que muestran los navegadores. La única forma que hay de modificarlo es asíncronamente, bloqueando página  con un Modal. Esto significa que el código de JavaScript no se paralizará esperando una respuesta del usuario, sino que abrirá la ventana y el código subsiguiente a la llamada del mensaje de alerta o confirmación, se seguirá ejecutando.

Tanto con JQuery como con MooTools, se puede implementar este Modal.

En la página oficial de MooTools se pueden encontrar gran cantidad de plugins para este tipo de interfaz. Un ejemplo:


Los plugins oficiales para JQuery se pueden encontrar en la página oficial de JQueryUI:


Aquí les mostraré cómo se hace con JQuery, pero la misma secuencia se puede usar con MooTools, lo que cambia es el código a utilizar y, claro está, las llamadas a los JavaScript desde la cabecera de nuestra página.

Para los mensajes de alerta


Este caso es simple, porque sólo muestra el formulario con un mensaje y un botón 'Ok', que puede llevar cualquier texto:



function alerta(mensaje)
{
$( "#div-dialogo" ).dialog( "destroy" );

/* Si tenemos saltos de línea con \n, 
* lo transformamos a <br>, para que lo interprete HTML
*/
var mensaje=mensaje.split('\n').join('<br>');

/*Le damos estilo al mensaje*/
var mostrar = '<p style="font-size: 15px;"><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>' + mensaje + '</p>';

/*Este es un equivalente a innerHTML, pero en JQuery*/
$( "#div-dialogo" ).html(mostrar);

/*Con la opción autoOpen, abrimos automáticamente el diálogo*/
$( "#div-dialogo" ).dialog({
bgiframe: true,
autoOpen: true,
minHeight: 200,
width: 500,
closeOnEscape: false,
draggable: true,
resizable: false,
title: "Mensaje",
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "destroy" );
}
}
});
}

Para los mensajes de confirmar una respuesta


Para este mensaje necesitamos recibir una respuesta, por si tenemos más de una opción y saber cuál escogimos. Le coloqué un segundo parámetro para valores extra:


function confirmar(mensaje, params)
{
/*Idem alerta*/
var mensaje=mensaje.split('\n').join('<br>');

/*Idem alerta*/
var mostrar = '<p style="font-size: 15px;"><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>' + mensaje + '</p>';

/*Idem alerta*/
$("#div-dialogo").html(mostrar);

/*Enviamos los parámetros a params*/
$( "#div-dialogo" ).data("params", params);

$( "#div-dialogo" ).dialog({
bgiframe: true,
autoOpen: true,
  minHeight: 200,
  width: 500,
  closeOnEscape: false,
  draggable: true,
  resizable: false,
title: "Confirme",
modal: true,
  buttons: {
     'Sí': function(param){
      $(this).dialog('destroy');

      /* Si la respuesta al usuario fue 'Sí', 
       * llamamos a una función que ejecutará lo que
       * queramos como respuesta al usuario.
       * Esta será respuestaConfirmar().
       */
     respuestaConfirmar($(this).data("params"));
  },
   'No': function(param){
    $(this).dialog('destroy');
   }
}

});
}

Por ejemplo, la respuesta podría ser, recargar un div con AJAX:

function respuestaConfirmar(params)
{
abrirAJAX(params.pagina+"?"+params.parametros, params.div, params.tipo_envio);
}

Llamando a la función confirmar, podemos utilizar el siguiente código, desde donde le pasamos los parámetros que usamos en respuestaConfirmar():

function llamadaConfirmar(CI_estudiante, nombre_estudiante, pregunta)
{
var params = {
 "pagina":"mostrar_mensaje",
"parametros":"CI_estudiante="+CI_estudiante+"&nombre_estudiante="+nombre_estudiante,
"div":"div-principal",
"tipo_envio":"post"};

 confirmar(pregunta, params);
}

Código HTML


Para ambos casos, necesitamos un div:


<div id="div-dialogo">
</div>

Y a la final, pueden fusionar ambos mensajes, Alerta y Confirmar, en una misma función con un simple IF :D.

Saludos y espero sus comentarios... xD

LATINCHAIN PLATFORM



news.latin-chain.com/
LatinChain Platform: Pi Hackathon winner 2021.
Welcome to LatinChain Ecosystem portal on Pi Network cryptocurrency ecosystem. Get utility usage bonus by using Mainnet and Testnet.


Understanding the LatinChain Ecosystem

Your gateway to decentralized applications on the Pi Network.


Welcome to the LatinChain Ecosystem portal. As a decentralized application (dApp) built on the Pi Network, our goal is to provide real utility and seamless interaction for the Pi community. Whether you are a developer, a pioneer, or a casual user, understanding the difference between our Mainnet and Testnet environments is crucial for maximizing your experience.



Staking Pi to Boost Rank

Did you know you can directly support the growth of LatinChain Mainnet?

By Staking Pi on our app within the Pi Browser, you help boost our ranking in the ecosystem directory. A higher rank means more visibility, bringing more Pioneers into our community and increasing the value of the network for everyone.

Support us today and help LatinChain reach the top!



Why Choose the Mainnet?

The LatinChain Mainnet (latinchain.pinet.com) is the live production environment where real value is exchanged. By accessing the Mainnet, you are interacting with the fully operational version of our blockchain application.

  • Real Utility: Every action contributes to the genuine activity of the network.
  • Verified Status: Users who choose to support the ecosystem via donations can unlock "Verified" status. This signals your commitment to the community.
  • Double Utility Bonus: Active usage on the Mainnet contributes to your Pi utility usage bonus.


The Role of the Testnet

The Testnet serves as our sandbox environment. It is designed for users who want to explore new features, test transaction flows, or understand the mechanics of the LatinChain token without using real Pi. It is the perfect training ground for new pioneers to get comfortable with Web3 interactions before moving to the Mainnet.



How the LatinChain Token Works

LatinChain is designed to foster a digital economy within the Pi Browser. By participating in either network, you are helping to stress-test and improve a growing financial ecosystem.



Select an option above to begin your journey.

The Evolution of Cryptocurrency: From Bitcoin's Genesis to Pi Network's Ecosystem (2008-nowadays)

The world of finance was forever changed in the aftermath of the 2008 global financial crisis. What started as an obscure proposal on a cryptography mailing list has transformed into a global technological revolution. Here is the journey of cryptocurrency from its inception to the present day.



The Genesis: Bitcoin and the Decentralized Dream (2008-2010)

In October 2008, an anonymous entity named Satoshi Nakamoto published a whitepaper titled "Bitcoin: A Peer-to-Peer Electronic Cash System." It introduced a revolutionary concept: a decentralized digital currency that required no central bank or administrator.

  • The Genesis Block: On January 3, 2009, the first block of the Bitcoin network was mined, setting the foundation for a new financial paradigm.
  • Proof of Work: This brilliant consensus mechanism solved the double-spending problem, ensuring complete trust in a trustless digital environment.



Programmable Money: Ethereum and the DeFi Explosion (2015-2021)

While Bitcoin proved the concept of digital scarcity, developers soon realized blockchain technology could do much more. In 2015, Ethereum launched, introducing "smart contracts"—self-executing code that lives directly on the blockchain.

  • Decentralized Finance (DeFi): Ethereum enabled the creation of lending platforms, decentralized exchanges, and automated market makers.
  • Mainstream Awareness: By 2021, the crypto market reached unprecedented heights, driven by global retail interest, digital art (NFTs), and the exciting promise of Web3.



Maturation and Institutional Adoption (2022-2024)

Following the euphoric highs of previous years, the industry entered a vital period of maturation. The global focus shifted from pure speculation to building robust, scalable infrastructure.

  • Layer 2 Solutions: New networks built on top of base blockchains made transactions significantly faster and cheaper.
  • Wall Street Entry: Major traditional financial institutions embraced Bitcoin ETFs, permanently cementing cryptocurrency as a legitimate and highly sought-after asset class.



The Accessibility Revolution: Pi Network (2025-nowadays)

Despite massive industry growth, a major barrier remained: traditional crypto mining was expensive and technically complex. Enter Pi Network, a visionary project designed to put cryptocurrency directly into the hands of everyday people. By nowadays, Pi Network has beautifully solidified its vision of creating a truly inclusive digital economy.

  • Mobile-First Innovation: Pi revolutionized accessibility by allowing users to mine directly from their smartphones without draining battery life or data.
  • Global Community: It successfully built one of the largest, most engaged, and widely distributed communities in the entire Web3 space.
  • Everyday Utility: With a robust ecosystem of decentralized applications (dApps) and an innovative native KYC solution, Pi Network empowers millions of everyday users to transact, build, and interact seamlessly.



Takeaway: The journey from 2008 to nowadays highlights a monumental shift from niche cryptography to universal accessibility, paving the way for a financial future that truly includes everyone.

Comments

Popular posts from this blog

Pi Network Apps published on Pi Network Ecosystem

Proyecto para Red Social gigante (Giant Social Network project)

Sígueme en mis Redes Sociales (Follow me in my Social Networks). OpenSource Expert 🇻🇪