If you are looking for the event under an external script, you can use the addEventListener
method to add the click event to your element, and the function that will be executed when that event is triggered.
Original answer
HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="a">Hola</div>
<!-- Tu script externo debería estar aquí, casi terminando el elemento body -->
<script src="eventoclick_ext.js"></script>
</body>
</html>
JavaScript ( eventoclick_ext.js
)
/* Elemento DIV que cambia su texto */
var a = document.getElementById("a");
/* Se agrega el evento al elemento */
a.addEventListener("click", changeText);
/* Función que se gatilla al hacer click en el elemento DIV */
function changeText() {
if (a.innerHTML == "Hola") {
a.innerHTML = "Mundo";
} else if (a.innerHTML == "Mundo") {
a.innerHTML = "Hola";
}
}
Additional: If the JS script is located in the element <head>
HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="eventoclick_ext.js"></script>
</head>
<body function>
<div id="a">Hola</div>
</body>
</html>
JavaScript ( eventoclick_ext.js
)
/* Al cargar la página se gatilla el listener */
window.addEventListener("load", main);
function main() {
/* Elemento DIV que cambia su texto*/
var a = document.getElementById("a");
/* Se agrega el evento */
a.addEventListener("click", changeText);
/* Función que se gatilla al hacer click en el elemento DIV */
function changeText() {
if (a.innerHTML == "Hola") {
a.innerHTML = "Mundo";
} else if (a.innerHTML == "Mundo") {
a.innerHTML = "Hola";
}
}
}