JavaScript fácil para páginas web. Códigos y ejemplos prácticos

Escribir con JavaScript


Con JavaScript se puede escribir en una página texto o código HTML (imágenes, enlaces, marcos, etc.) ya sea de forma directa o interactiva.
Para eso se pueden emplear las funciones document.write(), innerHTML, así como crear elementos con createElement() o agregarlos con appendChild().

Ejemplos

✔ Esta línea se ha escrito directamente con document.write()
✔ Esta línea se ha escrito directamente con innerHTML
✔ La siguiente imagen se escribe, pero solo después que la página termine de cargar todos sus elementos, usando la función addEventListener.
Imagen de prueba


Funciones más utilizadas en Javascript


¿Qué son las funciones?

Una función es un pedazo de código que permanece inactivo hasta que es llamada por un evento determinado por su nombre.
En este ejemplo se llama con un botón.
<script>
function popup() {
    alert("Hola gente")
}
</script>
<button type="button" onclick="popup()">Probar función</button>


Las funciones cuando son sencillas, también se pueden llamar con un enlace, incluyendo javascript y la función en la propiedad HREF.
Algunos ejemplos. Pruébalos.
✔ Mensaje con un alerta
✔ Compartir en Facebook
✔ Imprimir esta página
✔ Refrescar esta página
Código empleado:
<a href="javascript:(function(){alert('Hola gente')})()">Mensaje</a>
<a href="javascript:void(window.open('https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(location)));">Facebook</a>
<a href="javascript:window.print();">Imprimir</a>
<a href="javascript:window.location.reload();">Refrescar</a>
Ojo. Cuando se usa JavaScript en los enlaces, para abreviar el código, el navegador lo considera como si se tratara de una dirección URL, por lo que no deben existir espacios en el código y si son necesarios se tienen que escapar (%20).
Es necesario principalmente, al crear Bookmarklets
Usa la siguiente herramienta: Escapar y codificar caracteres de direcciones URL a hexadecimal

Alertas

Un alerta es una función que se usa para mostrar un mensaje en un cuadro, después de realizar alguna acción, que puede ser presionar un enlace, un botón, dar clic en un contenedor o cualquier otro evento.
Es necesario confirmar para cerrar el cuadro.

Código empleado:
<button type="button" onclick="alert('Esto es un cuadro de alerta')">Probar alerta</button>

Confirm

La función confirm es similar a las alertas, un pequeño cuadro de dialogo con un cuadro de confirmación.
La diferencia es que ofrece dos opciones: "Aceptar" para confirmar el mensaje y "Cancelar" si no se está de acuerdo con la petición expresada.
En ambos caso se estable una acción a realizar.
Se usa de la siguiente forma:
<script>
function confirmacion() {
	var pregunta = confirm("¿Deseas visitar la página principal?")
	if (pregunta){
		alert("Te envío allí rápidamente")
		window.location = "https://norfipc.com/";
	}
	else{
		alert("Quizás en otro momento...\n Gracias de todas formas")
	}
}
</script>
<button type="button" onclick="confirmacion()" >Probar confirm</button>


Variables

El propósito de una variable es guardar información que pueda ser utilizada más tarde.
Es un nombre simbólico que representa el dato que el usuario introduce y guarda.
Ejemplo de su uso.
<script> 
var age = 18;
var ella = 'El señor';
var el = 'La señora';
document.write(ella + " tiene " + age + " años\n");
document.write(el + " tiene " + age + " años");
</script>
El resultado se mostrará de la siguiente forma:
El señor tiene 18 años
La señora tiene 18 años

Prompt

Prompt es usado para introducir información por parte del usuario, la que podrá ser usada por otras funciones.
<script>
function prompter() {
var reply = prompt("Buenas ¿cuál es tu nombre?", "")
alert ( "Es un gusto tenerte aquí " + reply + "!")
}
</script>
<button type="button" onclick="prompter()">Probar prompt</button>

Ejemplos prácticos del uso de Javascript


Hacer operaciones matemáticas con Javascript

X

Copia el código más abajo y personalízalo a tu gusto con CSS.


Cambiar el estilo de las páginas web con Javascript

El estilo de las páginas web se puede modificar de forma interactiva (sin tener que refrescar la página desde el servidor) usando el objeto Estilo.
Esto puede resultar muy práctico, un ejemplo son los Bookmarklets usados para mejorar la accesibilidad de las paginas (tamaño del texto, color, eliminar publicidad, etc.)


Lee mas información con varios ejemplos prácticos: Como cambiar y modificar el estilo CSS de las páginas web con Javascript

Códigos de JavaScript para experimentar


Códigos de ejemplo para probar sencillas funciones de JavaScript.
Para usarlos cópialos y pégalos en un documento de texto plano (Notepad), renombra su extensión a HTML y ábrelos con el navegador.

Convertir texto en mayúsculas, minúsculas y capitalizar

<!DOCTYPE html>
<html lang="es">
<head>
</head>
<body>
<script>
function makeLowercase() {
document.form1.outstring.value = document.form1.instring.value.toLowerCase();}
function makeUppercase() {
document.form1.outstring.value = document.form1.instring.value.toUpperCase();}
String.prototype.capitalize = function(){
   return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
  };
function capWords() {
var inputString = document.form1.instring; 
var outputString = document.form1.outstring; 
outputString.value = inputString.value.capitalize();
}
</script>
<h1>Convertir texto en mayúsculas, minúsculas y capitalizar</h1>
<form name="form1" method="post">
<input name="instring" type="text" value="CONVIERTELO" size="30">
<input type="button" name="Convert" value="Minúsculas" onClick="makeLowercase();">
<input type="button" name="Convert" value="Mayúsculas" onClick="makeUppercase();">
<input type="button" name="Capitalize" value="Capitalizar" onClick="capWords();">
<input name="outstring" type="text" value="" size="30">
</form>
</body>
</html>    


Calculadora

<!DOCTYPE html>
<html lang="es">
<head>
</head>
<body>
<h1>Calculadora</h1>
<input type="text" id="arg1" size="1"> X <input type="text" id="arg2" size="1">
<input type="button" value="Calcular!" onclick="calc()"> 
<div id="result"></div>
<script type="text/javascript">
function calc(){
var argOne=document.getElementById('arg1').value; 
var argTwo=document.getElementById('arg2').value;
var ans=(argOne*argTwo); 
document.getElementById('result').innerHTML=argOne + ' multiplicado por ' + argTwo + ' es igual a ' + ans;
}
</script>
</body>
</html>   


Dos formas de mostrar la fecha

<!DOCTYPE html>
<html lang="es">
<head>
</head>
<body>
<h1>Dos formas de mostrar la fecha</h1>
<script>
var date=new Date();var d=date.getDate();var day=(d<10)?'0'+d:d;var m=date.getMonth()+1;var month=(m<10)?'0'+m:m;var yy=date.getYear();var year=(yy<1000)?yy+1900:yy;document.write(day+"/"+month+"/"+year);
</script><br>
<script>
function makeArray(){for(i=0;i<makeArray.arguments.length;i++)this[i+1]=makeArray.arguments[i]}var months=new makeArray('Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre');var date=new Date();var day=date.getDate();var month=date.getMonth()+1;var yy=date.getYear();var year=(yy<1000)?yy+1900:yy;document.write("Hoy es "+day+ " de "+months[month]+" del "+year);
</script>
</body>
</html>    


Botón huidizo

<!DOCTYPE html>
<html lang="es">
<head>
<style>
div.c2 {position:absolute; left:300px; top:300px; width:50px; height:50px;}
div.c1 {position:absolute; left:350px; top:300px; width:50px; height:50px;}
</style>
</head>
<body>
<h1>Botón huidizo</h1>
<script>
 var flag=1;function t(){if(flag==1){N.style.top="75px";N.style.left="700px"}if(flag==2){N.style.top="115px";N.style.left="100px"}if(flag==3){N.style.top="300px";N.style.left="350px"}flag=flag+1;if(flag==4){flag=1}}function al(){alert("Correcto!")}
</script>
NorfiPC es un sitio es muy interesante?
    <div id="N" class="c1">
      <form>
        <input type="button" value="NO" onmouseover="t()" />
      </form>
    </div>
    <div id="Y" class="c2">
      <form>
        <input type="button" value="SI" onclick="al()" />
      </form>
    </div>
</body>
</html>   


Mostrar coordenadas del ratón

<!DOCTYPE html>
<html lang="es">
<head>
</head>
<body>
<h1>Mostrar coordenadas del ratón</h1>
<form name="Show">
X <input type="text" name="MouseX" value="0" size="4"><br>
Y <input type="text" name="MouseY" value="0" size="4"><br>
</form>
<script>
var IE = document.all?true:false;
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;
var tempX = 0;
var tempY = 0;
function getMouseXY(e) {
if (IE) {tempX = event.clientX + document.body.scrollLeft;
tempY = event.clientY + document.body.scrollTop;}
else {tempX = e.pageX;tempY = e.pageY;}  
if (tempX < 0){tempX = 0;}
if (tempY < 0){tempY = 0;}  
document.Show.MouseX.value = tempX;
document.Show.MouseY.value = tempY;
return true;}
</script>
</body>
</html>    


Efecto de La Matrix

<!DOCTYPE html>
<html lang="es">
<head>
<style>
.matrix {font-size:10px;text-align:center;width:10px;}
</style>
</head>
<body>
<h1>Efecto de La Matrix con Javascript</h1>
<script>
var rows=11;var speed=10;var reveal=2;var effectalign="default"
var w3c=document.getElementById&&!window.opera;;var ie45=document.all&&!window.opera;var ma_tab,matemp,ma_bod,ma_row,x,y,columns,ma_txt,ma_cho;var m_coch=new Array();var m_copo=new Array();window.onload=function(){if(!w3c&&!ie45)return
var matrix=(w3c)?document.getElementById("matrix"):document.all["matrix"];ma_txt=(w3c)?matrix.firstChild.nodeValue:matrix.innerHTML;ma_txt=" "+ma_txt+" ";columns=ma_txt.length;if(w3c){while(matrix.childNodes.length)matrix.removeChild(matrix.childNodes[0]);ma_tab=document.createElement("table");ma_tab.setAttribute("border",0);ma_tab.setAttribute("align",effectalign);ma_tab.style.backgroundColor="#000000";ma_bod=document.createElement("tbody");for(x=0;x<rows;x++){ma_row=document.createElement("tr");for(y=0;y<columns;y++){matemp=document.createElement("td");matemp.setAttribute("id","Mx"+x+"y"+y);matemp.className="matrix";matemp.appendChild(document.createTextNode(String.fromCharCode(160)));ma_row.appendChild(matemp);}
ma_bod.appendChild(ma_row);}
ma_tab.appendChild(ma_bod);matrix.appendChild(ma_tab);}else{ma_tab='<ta'+'ble align="'+effectalign+'" border="0" style="background-color:#000000">';for(var x=0;x<rows;x++){ma_tab+='<t'+'r>';for(var y=0;y<columns;y++){ma_tab+='<t'+'d class="matrix" id="Mx'+x+'y'+y+'">&nbsp;</'+'td>';}
ma_tab+='</'+'tr>';}
ma_tab+='</'+'table>';matrix.innerHTML=ma_tab;}
ma_cho=ma_txt;for(x=0;x<columns;x++){ma_cho+=String.fromCharCode(32+Math.floor(Math.random()*94));m_copo[x]=0;}
ma_bod=setInterval("mytricks()",speed);}
function mytricks(){x=0;for(y=0;y<columns;y++){x=x+(m_copo[y]==100);ma_row=m_copo[y]%100;if(ma_row&&m_copo[y]<100){if(ma_row<rows+1){if(w3c){matemp=document.getElementById("Mx"+(ma_row-1)+"y"+y);matemp.firstChild.nodeValue=m_coch[y];}
else{matemp=document.all["Mx"+(ma_row-1)+"y"+y];matemp.innerHTML=m_coch[y];}
matemp.style.color="#33ff66";matemp.style.fontWeight="bold";}
if(ma_row>1&&ma_row<rows+2){matemp=(w3c)?document.getElementById("Mx"+(ma_row-2)+"y"+y):document.all["Mx"+(ma_row-2)+"y"+y];matemp.style.fontWeight="normal";matemp.style.color="#00ff00";}
if(ma_row>2){matemp=(w3c)?document.getElementById("Mx"+(ma_row-3)+"y"+y):document.all["Mx"+(ma_row-3)+"y"+y];matemp.style.color="#009900";}
if(ma_row<Math.floor(rows/2)+1)m_copo[y]++;else if(ma_row==Math.floor(rows/2)+1&&m_coch[y]==ma_txt.charAt(y))zoomer(y);else if(ma_row<rows+2)m_copo[y]++;else if(m_copo[y]<100)m_copo[y]=0;}
else if(Math.random()>0.9&&m_copo[y]<100){m_coch[y]=ma_cho.charAt(Math.floor(Math.random()*ma_cho.length));m_copo[y]++;}}
if(x==columns)clearInterval(ma_bod);}
function zoomer(ycol){var mtmp,mtem,ytmp;if(m_copo[ycol]==Math.floor(rows/2)+1){for(ytmp=0;ytmp<rows;ytmp++){if(w3c){mtmp=document.getElementById("Mx"+ytmp+"y"+ycol);mtmp.firstChild.nodeValue=m_coch[ycol];}
else{mtmp=document.all["Mx"+ytmp+"y"+ycol];mtmp.innerHTML=m_coch[ycol];}
mtmp.style.color="#33ff66";mtmp.style.fontWeight="bold";}
if(Math.random()<reveal){mtmp=ma_cho.indexOf(ma_txt.charAt(ycol));ma_cho=ma_cho.substring(0,mtmp)+ma_cho.substring(mtmp+1,ma_cho.length);}
if(Math.random()<reveal-1)ma_cho=ma_cho.substring(0,ma_cho.length-1);m_copo[ycol]+=199;setTimeout("zoomer("+ycol+")",speed);}
else if(m_copo[ycol]>200){if(w3c){mtmp=document.getElementById("Mx"+(m_copo[ycol]-201)+"y"+ycol);mtem=document.getElementById("Mx"+(200+rows-m_copo[ycol]--)+"y"+ycol);}
else{mtmp=document.all["Mx"+(m_copo[ycol]-201)+"y"+ycol];mtem=document.all["Mx"+(200+rows-m_copo[ycol]--)+"y"+ycol];}
mtmp.style.fontWeight="normal";mtem.style.fontWeight="normal";setTimeout("zoomer("+ycol+")",speed);}
else if(m_copo[ycol]==200)m_copo[ycol]=100+Math.floor(rows/2);if(m_copo[ycol]>100&&m_copo[ycol]<200){if(w3c){mtmp=document.getElementById("Mx"+(m_copo[ycol]-101)+"y"+ycol);mtmp.firstChild.nodeValue=String.fromCharCode(160);mtem=document.getElementById("Mx"+(100+rows-m_copo[ycol]--)+"y"+ycol);mtem.firstChild.nodeValue=String.fromCharCode(160);}
else{mtmp=document.all["Mx"+(m_copo[ycol]-101)+"y"+ycol];mtmp.innerHTML=String.fromCharCode(160);mtem=document.all["Mx"+(100+rows-m_copo[ycol]--)+"y"+ycol];mtem.innerHTML=String.fromCharCode(160);}
setTimeout("zoomer("+ycol+")",speed);}}
</script>
<div id="matrix">&nbsp; Efecto matrix con Javascript &nbsp;</div>
</body>
</html>    


Herramientas


Editor de código Javascript

Sencillo editor que puedes abrir en el enlace más abajo, abre una pequeña ventana donde puedes introducir o pegar las funciones y probar el resultado.
Un ejemplo: copia y pega: alert('Esta es una alerta!') y selecciona Probar.
➔ Editor de código Javascript

Si te interesó el artículo, este sitio está lleno de páginas que contienen efectos que usan código Javascript, también hay muchas que tratan el tema y contienen bastante código para crear funciones copiando y pegando.
Cualquier efecto en esta página que te interese, mira el código fuente.

Enlace de esta pagina: https://norfipc.com/web/javascript-facil-paginas-web-ejemplos.html

Ejemplos de juegos hechos con Javascript

Enlace al juego Tic Tac
Enlace al juego del Ahorcado

Comentarios

Entradas más populares de este blog

Variables Javascript

Botones

Texto parpadeante