Add Event Handler to HTML Element Using JavaScript

Add event handler to HTML element using javascript

You can add event listener.

Smth. like this:

 var el = document.getElementById("p1");
if (el.addEventListener) {
el.addEventListener("click", yourFunction, false);
} else {
el.attachEvent('onclick', yourFunction);
}

(thanks @Reorx)

Explanation Here

Complete code (tested in Chrome&IE7):

<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<script type="text/javascript">
window.onload =function (){
var el = document.getElementById("p1");
if (el.addEventListener) {
el.addEventListener("click", yourFunction, false);
} else {
el.attachEvent('onclick', yourFunction);
}
};
function yourFunction(){
alert("test");
}
</script>
</head>
<body>
<p id="p1">test</p>

</body>
</html>

How to add event with Javascript to an html tag

Use querySelector and addEventListener:

document.addEventListener('DOMContentLoaded', function () {    var dataLayer = [];    var d = document.querySelector("#testid a[name=button1]");    d.addEventListener("click", function () {        dataLayer.push({ 'event': 'button1-click' });    });});
<!DOCTYPE html><html>
<head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>repl.it</title> <link href="style.css" rel="stylesheet" type="text/css" /></head>
<body> <div id="testid"> <div> <div> <a href="#" name="button1">Button 1</a> <div> <div> <div> </div> </div> </div> </div> </div> </div> <script src="script.js">
</script></body>
</html>

Add Event Listener to Collection of HTML Elements

Adding eventlistener to each of them is not advisable. May be this can help:

http://jsfiddle.net/b8gotLL6/

document.getElementById('parent').addEventListener('click', function(e){
alert(e.target.value);
})

And if you only want to do using getElementsByTagName or getElementsByClassName, then i guess you need to iterate for the array returned.

JavaScript attach events to elements rendered dynamically

You have to reload all.js after each new element. That is the only solution I can think of.

After action that creates an element you'll call a function:

// removed, see Edit

this shall reevalute all.js and listeners from all.js shall attach to elements being in DOM.

This is very inefficient solution, so if you make several dynamic updates, reload all.js at the end of all updates, not after every single update.

This also mean, that some statefull variables from all.js might be reinitialized, counters may be reset to zero, etc.

I would personally never do this kind of piggy patching, but if you have no other choice, give it a try.

Edit

Tested working code

function reloadAllJs(){
var path = "all.js"
, oldScript = document.querySelector("script[src^='" + path + "']")
, newScript = document.createElement("script")
;
// adding random get parameter to prevent caching
newScript.src = path + "?timestamp=" + Date.now();
oldScript.parentNode.replaceChild(newScript, oldScript);
}

querySelector and Date.now()are IE9+ compatible, for support IE8- the code must be modified.

Update

IE8- compatible version (tested in IE7)

function reloadAllJs(){
var path = "all.js"
, scripts = document.getElementsByTagName("script")
, oldScript
, newScript = document.createElement("script")
;

for(var i = 0, s; s = scripts[i]; i++) {
if (s.src.indexOf(path) !== -1) {
oldScript = s;
break;
}
}

// adding random get parameter to prevent caching
newScript.src = path + "?timestamp=" + (new Date()).getTime();
oldScript.parentNode.replaceChild(newScript, oldScript);
}

Note: IE8 does not support addEventListener (it has very similar method attachEvent ), so if your all.js relies on addEventListener, then all.js is only IE9+ compatible.

Event listener in HTML vs. addEventListener

Use the first version - but dont use querySelectorAll if you only have one form. If you have only one form, give it an ID and use document.getElementById instead.

If you have many, I would delegate:

<div id="formContainer">
<form class="my-form">
<input type="submit"/>
</form>
<form class="my-form">
<input type="submit"/>
</form>
</div>
<script>
document.getElementById("formContainer").addEventListener("submit", function(e) {
e.preventDefault();
console.log("Data received");
});

</script>

To do the second, we used to do this in the previous millenium

<form onsubmit="return doSomething()">
<input type="submit"/>
</form>
<script>
function doSomething() {
console.log("Data received");
return false
}
</script>

but it is not recommended

Is there a way to attach event handlers to an HTML element as soon as the element is present on the page

Three ideas:

  1. Use an attribute in the HTML like onclick="foo()". This will be in force immediately.

  2. You could place a <script> tag immediately after the HTML element embedded in the HTML and have that script add the event handler. All DOM elements located before a script are guaranteed to be parsed and ready.

  3. You could make the element by initially hidden (either inline style specification or CSS), then wait until it's in the DOM, run your script to install the event handler and then make the object visible. If you use visibility: hidden, then the document will lay out as normal and the content can be made visibility: visible after installing the event handler.

The browser doesn't offer access to the object until it's parsed and in the DOM so any script that wants to operate on it has to either be physically located after the DOM element or has to wait for an event to occur that indicates the DOM has been loaded.

The browser doesn't offer an event when a DOM element is parsed, but not yet visible that would offer you a chance to operate on it at that moment so you have to work around your issue with one of these other methods.

Add event handler to an element that not yet exists using on()?

$('body').on('click','p#two', function() {
console.log('p#two clicked');
});

you can also use

$(document).on('click', 'p#two', function() {

});

Read more about .on()

you can also use .delegate()

$('body').delegate('#two', 'click', function() {

});

How to add event listener with function callback in html inside a class?

You have to create the element -> something like this

class Container {
constructor (hook) {
this.hook = '#' + hook;
this.addDiv = this.addDiv.bind(this);
this.fireMe = this.fireMe.bind(this);
this.init = this.init.bind(this);
this.init();
}

addDiv () {
const div = document.createElement('div');
div.textContent = 'FIRE ME';
div.addEventListener('click', this.fireMe );
document.querySelector(this.hook).innerHTML = div;
}

fireMe () {
console.log('hello!');
}

init () {
this.addDiv();
}
}

const div = new Container('app');


Related Topics



Leave a reply



Submit