viernes, 8 de noviembre de 2013

Introducción a Java Script y HTML DOM

Introducción a Java Script

Después de haber aprendido como funciona un Servlets, JSP, Filters, Web Listeners, acceso a datos con Java. Vamos a aprender a utilizar diferentes tecnologías Web para enriquecer nuestras aplicaciones.

En este Post vamos a ver sobre Java Script utilizando un Tutorial de   W3 Schools.


Introducción

Java script es un lenguaje ligero de utilizar, que se puede colocar en páginas Web y puede ser ejecutado en Navegadores de Internet(Browser), Java Script es Fácil de Aprender.

Como utilizar


Se utiliza  en el HTML con la etiqueta html <script>

<script>
alert("My First JavaScript");
</script>

Se puede hacer referencias de recursos javascript externos, mediante un URL

Example

<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>

Probar

Salida

Java Script se utiliza para manipular elementos HTML en una página

Para acceder a los elementos Java Script se utiliza un objeto implicito "document" y el método "getElementById"

document.getElementById(id


Example

Cambiar contenido de un Html específico:
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<p id="demo">My First Paragraph</p>

<script>
document.getElementById("demo").innerHTML="My First JavaScript";
</script>


</body>
</html>

Try it yourself »

Example

Escribir en el HTML
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<script>
document.write("<p>My First JavaScript</p>");
</script>


</body>
</html>

Try it yourself »

Sentencias

Las sentencias javascript son "comandos" para el Browser,  Cada sentencia es una orden de que tiene que hacer el Browser.

document.getElementById("demo").innerHTML="Hello Dolly";


Normalmente, se necesita terminar la sentencia con ";"

Example

document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";

Try it yourself »

Bloques

Los Bloques están marcados por "{" y finaliza con "}" así como en el lenguaje de programación "Java"

Example

function myFunction()
{
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
}

Try it yourself »

JavaScript es Sensible a las Mayúsculas

Es importante saber que los nombres de funciones, variables, etc. son sencibles a las Mayúscula.

ejemplo

var hola = null;
Hola = 1;

Hola y hola son nombres de diferentes y hola no es igual 1

Comentarios

Comentario simple

Example

// Write to a heading:
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
// Write to a paragraph:
document.getElementById("myP").innerHTML="This is my first paragraph.";

Try it yourself »
Comentario Multilinea

Example

/*
The code below will write
to a heading and to a paragraph,
and will represent the start of
my homepage:
*/
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";

Try it yourself »
Comentarios al finalizar lineas o sentencias

Example

var x=5;    // declare x and assign 5 to it
var y=x+2;  // declare y and assign x+2 to it

Try it yourself »

Variables

Se utiliza la palabra reservada var para declarar una variable, esa variable tendrá un alcance o vida en la misma o dentro de una sentencia o bloque.

Example

<p id="demo"></p>
var carname="Volvo";
document.getElementById("demo").innerHTML=carname;

Try it yourself »

var lastname="Doe", age=30, job="carpenter";



var lastname="Doe",
age=30,
job="carpenter";


var carname; //is undefined


Tipos de Datos

Las variables son de tipo dinámico

Example

var x;               // Ahora x es undefined
var x = 5;           // Ahora x es un Number
var x = "John";      // Ahora x es un String

Declaración de String

Example

var carname="Volvo XC60";
var carname='Volvo XC60';

Example

var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';

Try it yourself »

Declaración de Números

Example

var x1=34.00;      // con Decimales
var x2=34;         // sin Decimales


Declaración de Booleanos

var x=true;
var y=false;


Arreglos en Java Script

var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";

var cars=new Array("Saab","Volvo","BMW");

Example

var cars=["Saab","Volvo","BMW"];

Try it yourself »

Objetos

var person={firstname:"John", lastname:"Doe", id:5566};

Example

name=person.lastname;//asignar apellido de persona en name
name=person["lastname"];//asignar también apellido en name

Try it yourself »

Undefined y Null

Example

cars=null;
person=null;

Try it yourself »

Objetos

Casi todo en JavaScript puede ser un Object: Strings, Functions, Arrays, Dates.


Creando un Objeto

Example

person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";

Try it yourself »

Acceder a Propiedades de String
var message="Hello World!";
var x=message.length;


Invocar Métodos de Objetos

objectName.methodName()

Funciones

Example

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}

</script>
</head>

<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>

xample

<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>

Try it yourself »

Operadores

Operadores Aritméticos

Given that y=5, the table below explains the arithmetic operators:
OperatorDescriptionExampleResult of xResult of yTry it
+Additionx=y+275Try it »
-Subtractionx=y-235Try it »
*Multiplicationx=y*2105Try it »
/Divisionx=y/22.55Try it »
%Modulus (division remainder)x=y%215Try it »
++Incrementx=++y66Try it »
x=y++56Try it »
--Decrementx=--y44Try it »
x=y--54Try it »

Operadores de Asignación

Given that x=10 and y=5, the table below explains the assignment operators:
OperatorExampleSame AsResultTry it
=x=yx=5Try it »
+=x+=yx=x+yx=15Try it »
-=x-=yx=x-yx=5Try it »
*=x*=yx=x*yx=50Try it »
/=x/=yx=x/yx=2Try it »
%=x%=yx=x%yx=0Try it »


Example

Concatenar 2 o más Cadenas de Texto.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
The result of txt3 will be:
What a verynice day

Try it yourself »

Example

x=5+5;
y="5"+5;
z="Hello"+5;
The result of x,y, and z will be:
10
55
Hello5

Try it yourself »

Condicionantes

Operadores

Given that x=5, the table below explains the comparison operators:
OperatorDescriptionComparingReturnsTry it
==equal tox==8falseTry it »
x==5trueTry it »
===exactly equal to (equal value and equal type)x==="5"falseTry it »
x===5trueTry it »
!= not equalx!=8trueTry it »
!== not equal (different value or different type)x!=="5"trueTry it »
x!==5falseTry it »
> greater thanx>8falseTry it »
< less thanx<8trueTry it »
>= greater than or equal tox>=8falseTry it »
<= less than or equal tox<=8trueTry it »


Operadores Lógicos

Given that x=6 and y=3, the table below explains the logical operators:
OperatorDescriptionExample
&&and(x < 10 && y > 1) is true
||or(x==5 || y==5) is false
!not!(x==y) is true

Operador Condicional

Example

Example

If the variable age is a value below 18, the value of the variable voteable will be "Too young, otherwise the value ofvoteable will be "Old enough":
voteable=(age<18)?"Too young":"Old enough";

Try it yourself »


Sentencia IF


if (condition)
  {
  code to be executed if condition is true
  }

Example

Make a "Good day" greeting if the time is less than 20:00:
if (time<20)
  {
  x="Good day";
  }
The result of x will be:
Good day

Try it yourself »

Sentencia IF ELSE

Example

If the time is less than 20:00, you will get a "Good day" greeting, otherwise you will get a "Good evening" greeting
if (time<20)
  {
  x="Good day";
  }
else
  {
  x="Good evening";
  }
The result of x will be:
Good day

Sentencia IF ELSE ELSE


Example

If the time is less than 10:00, you will get a "Good morning" greeting, if not, but the time is less than 20:00, you will get a "Good day" greeting, otherwise you will get a "Good evening" greeting:
if (time<10)
  {
  x="Good morning";
  }
else if (time<20)
  {
  x="Good day";
  }
else
  {
  x="Good evening";
  }
The result of x will be:
Good day

Try it yourself »


Try it yourself »

Loops o Ciclos

For

You can write:

for (var i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
}

Try it yourself »

FOR IN

The For/In Loop

The JavaScript for/in statement loops through the properties of an object:

Example

var person={fname:"John",lname:"Doe",age:25};

for (x in person)
  {
  txt=txt + person[x];
  }

Try it yourself »


While


Example

while (i<5)
  {
  x=x + "The number is " + i + "<br>";
  i++;
  }

Try it yourself »

Do While


Example

do
  {
  x=x + "The number is " + i + "<br>";
  i++;
  }
while (i<5);

Try it yourself »

Breaks

for (i=0;i<10;i++)
  {
  if (i==3)
    {
    break;
    }
  x=x + "The number is " + i + "<br>";
  }

Try it yourself »


Errores

Manejo de Excepciones


Example

<!DOCTYPE html>
<html>
<head>
<script>
var txt="";
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.\n\n";
  txt+="Error description: " + err.message + "\n\n";
  txt+="Click OK to continue.\n\n";
  alert(txt);
  }
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()">
</body>

</html>

Try it yourself »

Validaciones


Ejemplo de Validación


function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}
The function above could be called when a form is submitted:

Example

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Try it yourself »

HTML DOM

Documento de Referencia de HTML DOM http://www.w3schools.com/jsref/default.asp




No hay comentarios:

Publicar un comentario