How to add an event to an element created with JavaScript

1

Create a button dynamically with javascript and now I want that when you click on it, a certain function will be executed that with jQuery would be as follows:

$(".elemento").on("load", function() {        
    // Codigo           
});

My question is how to do that but with pure JavaScript

    
asked by Jhoan Corrales 16.05.2018 в 00:35
source

4 answers

1

Natively JavaScript has the onclick property to handle the event in question. Here you can read more about the property.

For a dynamically created button;

var boton = document.createElement("button");
boton.innerHTML = "click";
document.body.appendChild(boton);

boton.onclick = function() {
  alert("Has hecho click");
};

And for an element of the DOM taking its ID;

var boton = document.getElementById("boton");

boton.onclick = function() {
  alert("Soy un botón");
}
<button id="boton">Haz click</button>

In your case, if you are working with the attribute class as in your example, if you have several buttons with the same class you should make a loop for to go through all the elements with that class and apply the property;

var botones = document.getElementsByClassName("boton");

for (var i=0;i<botones.length;i++) {
  botones[i].onclick = function() {
    alert(this.innerHTML);
  }
}
<button class="boton">Boton 1</button>
<button class="boton">Boton 2</button>
<button class="boton">Boton 3</button>
<button class="boton">Boton 4</button>
    
answered by 16.05.2018 / 12:47
source
1

There are two ways to achieve that, one way is using a listener with onClick , example in the code of button 1.

The other way would be adding listener from javascript with addEventListener

function onClick() {
  console.log('AAA');
}

document.getElementById('boton').addEventListener('click', onClick);
<input type="button" value="boton 1" onClick="onClick()">



<input type="button" value="boton 2" id="boton">
    
answered by 16.05.2018 в 01:22
0

correction

<input type="button" value="click" onClick="clickButton()">

and in javascript:

function clickButton() { 
  //código
}
    
answered by 16.05.2018 в 00:56
0

function funcion(){console.log("Boton Presionado")}

$("#boton1").click(funcion);
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
    <button id="boton1">Boton 1</button>
    <button id="boton2" onclick="funcion()"> Boton 2 </button>
</body>

<script>
</script>
</html>
    
answered by 16.05.2018 в 01:27