Mi viaje Full Stack en Java: aprendiendo JavaScript

Descubre cómo usar addEventListener y removeEventListener en JavaScript para manejar eventos del DOM, con ejemplos, hoisting y buenas prácticas.

3 sept 2025 • 2 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

addEventListener en JavaScript

El metodo addEventListener en JavaScript sirve para adjuntar un manejador de eventos a un elemento especifico del arbol del DOM. De esta forma el elemento puede reaccionar a acciones del usuario o del propio sistema como click, input, submit, keydown, scroll y muchas otras.

Sintaxis

target.addEventListener(evento, funcion)

target elemento del DOM al que se le vincula el evento

evento tipo de evento que se quiere escuchar por ejemplo click o input

funcion funcion que se ejecuta cuando el evento ocurre recibe como argumento el objeto Event

Ejemplo basico

<body> <button id=needtoclick>haz clic</button> <script> const btn = document.getElementById(needtoclick) btn.addEventListener(click, () => console.log(Boton pulsado)) </script> </body>

Ten en cuenta los nombres correctos de las APIs del navegador document en minusculas y addEventListener con todas sus letras

removeEventListener

Este metodo elimina un manejador de eventos previamente registrado sobre un elemento del DOM. Es util para limpiar recursos o evitar que un componente siga reaccionando cuando ya no es necesario.

Sintaxis

target.removeEventListener(evento, funcion)

Para que la eliminacion funcione la referencia de la funcion debe ser exactamente la misma que se paso al registrar el evento

Consejo si usas una funcion flecha anonima al registrar no podras eliminarla despues porque no tendras la misma referencia. En su lugar guarda la funcion en una variable o define la funcion con nombre.

Hoisting en JavaScript

El hoisting es el comportamiento por el cual ciertas declaraciones se procesan antes de ejecutar el codigo. En terminos practicos

Se elevan las declaraciones de funcion function nombre y las variables declaradas con var aunque estas ultimas quedan inicialmente como undefined

No se elevan las expresiones de funcion asignadas a let o const ni las propias declaraciones let y const que permanecen en zona muerta temporal hasta su linea de inicializacion

Ejemplo de funcion declarada con hoisting

addDeclaracion() function addDeclaracion(){ console.log(Funcion declarada) } addDeclaracion()

La llamada anterior a la declaracion funciona porque la definicion de la funcion se eleva

Ejemplo de funcion expresion sin hoisting

addExpresion() produce error de referencia const addExpresion = function(){ console.log(Funcion expresion) } addExpresion()

En este caso la llamada antes de la asignacion falla porque ni la variable const ni la expresion son accesibles antes de su inicializacion

Buenas practicas

Usa nombres de metodos correctos addEventListener y removeEventListener

Guarda en una variable la funcion manejadora para poder retirarla despues con removeEventListener

Prefiere const o let para variables y expresiones de funcion y declara siempre antes de usar para evitar errores de referencia

Comprueba opciones adicionales del tercer argumento por ejemplo capture o passive cuando necesites ajustar el comportamiento avanzado del listener

Feliz programacion

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat