28. Javascript¶
28.1 Primeros pasos Javascript¶
28.2 Bloques básicos jscript¶
28.2.1 Definir funciones¶
El siguiente ejemplo añade al final del documento dos elementos, un div y un párrafo:
function nuevoBloque(){
const body = document.body;
const panel = document.createElement('div');
panel.setAttribute('class','msgBox');
body.appendChild(panel);
const msg = document.createElement('p');
msg.textContent = 'This is a message box';
panel.appendChild(msg);
const closeBtn = document.createElement('button');
closeBtn.textContent = 'x';
panel.appendChild(closeBtn);
// otra acción:
closeBtn.addEventListener('click', () => panel.parentNode.removeChild(panel));
}
addEventListener(evento, función)
asocia el argumento evento a la función pasada en segundo lugar.
Se utiliza el DOM API para crear e insertar los elementos.
Podemos borrar la última línea de la función y fuera de esta añadir:
const btn = document.querySelector('button');
btn.addEventListener('click', nuevoBloque);
28.2.1.1 Funciones con argumentos.¶
Añadimos argumentos a la función
function nuevoBloque(msgText, tipoText){
const body = document.body;
const panel = document.createElement('div');
panel.setAttribute('class','msgBox');
body.appendChild(panel);
const msg = document.createElement('p');
msg.textContent = msgText;
panel.appendChild(msg);
const closeBtn = document.createElement('button');
closeBtn.textContent = 'x';
panel.appendChild(closeBtn);
// otra acción: closeBtn.addEventListener('click', () => panel.parentNode.removeChild(panel));
msg.
}
// actualizado
btn.addEventListener('click', () => nuevoBloque('Un mensaje distino'));
28.2.1.2 Return¶
Valores devuelto por las funciones.
28.2.2 Introducción a los eventos¶
Consultar el documento referencia de enventos DOM.
Ejemplos de eventos:
* The user selects, clicks, or hovers the cursor over a certain element.
* The user chooses a key on the keyboard.
* The user resizes or closes the browser window.
* A web page finishes loading.
* A form is submitted.
* A video is played, paused, or ends.
* An error occurs.
Para tratar los eventos se crea un event handler que suele ser un bloque de código javascript.
Ejemplo:
const btn = document.querySelector('button');
function random(number) {
return Math.floor(Math.random() * (number+1));
}
btn.addEventListener('click', () => {
const rndCol = `rgb(${random(255)}, ${random(255)}, ${random(255)})`;
document.body.style.backgroundColor = rndCol;
});
28.2.2.1 Usando addEventListner¶
El mecanismo recomendado es :
const btn = document.querySelector('button');
function random(number) {
return Math.floor(Math.random() * (number+1));
}
btn.addEventListener('click', () => {
const rndCol = `rgb(${random(255)}, ${random(255)}, ${random(255)})`;
document.body.style.backgroundColor = rndCol;
});
28.2.2.2 Otros eventos¶
First, make a local copy of random-color-addeventlistener.html, and open it in your browser. It's just a copy of the simple random color example we've played with already. Now try changing click to the following different values in turn, and observing the results in the example:
focus and blur — The color changes when the button is focused and unfocused; try pressing the tab to focus on the button and press the tab again to focus away from the button. These are often used to display information about filling in form fields when they are focused, or to display an error message if a form field is filled with an incorrect value. dblclick — The color changes only when the button is double-clicked. mouseover and mouseout — The color changes when the mouse pointer hovers over the button, or when the pointer moves off the button, respectively.
Ver ejemplo ran_color.
28.2.3 Eliminar gestores de eventos.¶
btn.removeEventListener('click', changeBackground);
28.2.4 Multiples gestores de eventos.¶
Para un evento se pueden crear multiples gestores:
myElement.addEventListener('click', functionA);
myElement.addEventListener('click', functionB);