Coder Social home page Coder Social logo

js-functions-workshop's Introduction

Taller de JavaScript: Funciones

Resultado

Autor: Eduardo Oviedo Blanco

Para usar este taller efectivamente, clone el código en su ambiente local.

git clone https://github.com/edWAR6/JS-Functions-Workshop.git

Si desea subir el taller en su repositorio personal. Cree un repositorio en su perfil, luego:

git remote set-url origin https://github.com/<tu usuario>/JS-Functions-Workshop.git

El nombre del repositorio puede cambiar. Siga las instrucciones y guarde sus cambios.

Propósito

Este taller muestra, de manera básica, la creación de funciones, funciones anónimas y el uso de parámetros.

Instrucciones

  1. Inicie creando la primer función, llamada displayMessage.
function displayMessage() {

}
  1. Dentro de la función anterior, defina e inicialice las constantes con los elementos HTML.
const html = document.querySelector('html');

const panel = document.createElement('div');
panel.setAttribute('class', 'msgBox');
html.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);
  1. Dentro de la misma función, cree una función anónima y asígnela al evento onclick del botón.
closeBtn.onclick = function() {
  panel.parentNode.removeChild(panel);
}
  1. Para probar nuestra función, agregue el siguiente llamado a la función temporalmente al final del archivo.
displayMessage();
  1. Ejecute la aplicación y analice el resultado.
  2. Comente o borre el llamado a la función que creó al final.
  3. Al inicio del archivo, agregue una declaración de un botón que corresponderá al botón en el HTML.
const btn = document.querySelector('button');
  1. Bajo la nueva constante, asigne la función al evento onclick del botón.
btn.onclick = displayMessage;
  1. Observe el avance hasta ahora.
  2. Para hacer más dinámico el ejemplo, agregue parámetros a la función.
function displayMessage(msgText, msgType) {
  ...
  1. Para poder usar el primer parámetro, cambie la instrucción que asigna la propiedad textContent del msg.
msg.textContent = msgText;
  1. Ahora asegúrese de enviar el primer parámetro, para esto en lugar de asignar la función directamente al evento onclick, será necesario crear una función anónima.
btn.onclick = function() {
  displayMessage('Woo, this is a different message!');
};
  1. Observe el avance hasta ahora.
  2. Para hacer funcionar el segundo parámetro, cambia el CSS correspondiente al ancho de la clase .msgBox.
width: 242px;
  1. Agregue las siguientes instrucciones a la clase .msgBox p.
padding-left: 82px;
background-position: 25px center;
background-repeat: no-repeat;
  1. Ahora, agregue las siguientes instrucciones al final de la función displayMessage.
if (msgType === 'warning') {
  msg.style.backgroundImage = 'url(images/warning.png)';
  panel.style.backgroundColor = 'red';
} else if (msgType === 'chat') {
  msg.style.backgroundImage = 'url(images/chat.png)';
  panel.style.backgroundColor = 'aqua';
} else {
  msg.style.paddingLeft = '20px';
}
  1. Finalmente, en el evento click del botón, cambie el llamado a la función por alguna de las siguientes líneas. Puede dejar cualquiera de las dos comentadas.
displayMessage('Your inbox is almost full — delete some mails', 'warning');
// displayMessage('Brian: Hi there, how are you today?','chat');

Conclusión

Es importante entender la diferencia entre una función y una función anónima. Además de darse cuenta que pueden existir dentro de otras funciones. Los parámetros son por defecto opcionales y pueden simplemente no usarse. Las funciones nos permiten tenér código reusable y el úso de parámetros nos permite tener funciones configurables.

js-functions-workshop's People

Contributors

eduardo-xyz avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.