Handling onclick event with pure JavaScript
All browsers support this (see example here):
mySelectedElement.onclick = function(e){
//your handler here
}
However, sometimes you want to add a handler (and not change the same one), and more generally when available you should use addEventListener
(needs shim for IE8-)
mySelectedElement.addEventListener("click",function(e){
//your handler here
},false);
Here is a working example:
var button = document.getElementById("myButton");
button.addEventListener("click",function(e){
button.disabled = "true";
},false);
And html:
<button id='myButton'>Hello</button>
(fiddle)
Here are some useful resources:
addEventListener
on mdn- The click event in the DOM specification
- Click example in the MDN JavaScript tutorial
Click event in plain JavaScript
You can do that in the following way:
var div = document.getElementById('myId');div.addEventListener('click', function(e){ console.log(this.getAttribute('id'))});
<div id="myId"> <div> <h2>First Div</h2> </div> <div> <h2>Second Div</h2> </div></div>
How to update the onclick event of the element using pure javascript?
You can try to use setAttribute
method, like this:
function func_x(input) { console.log('I\'m func_x function'); input.setAttribute('onclick', 'javascript:func_y()');}
function func_y() { console.log('I\'m func_y function');}
<input type="button" onclick="javascript:func_x(this)" value="MENU" id="btn">
Get li element onclick with pure javascript without applying onClick to each element
You could add an event listener to the parent ul
and then use e.target.id
to get the id
of the clicked element. Just check to make sure that the clicked element is actually an li
since it's possible you may not be clicking on one.
Example Here
var ul = document.getElementById('bulk'); // Parent
ul.addEventListener('click', function(e) {
if (e.target.tagName === 'LI'){
alert(e.target.id); // Check if the element is a LI
}
});
As pointed out in the comments, this approach won't work when the child of an li
is clicked. To solve this, you would need to check to see if the parent element of the clicked element is the one that the click event is attached to.
Example Here
var ul = document.getElementById('bulk'); // Parent
ul.addEventListener('click', function (e) {
var target = e.target; // Clicked element
while (target && target.parentNode !== ul) {
target = target.parentNode; // If the clicked element isn't a direct child
if(!target) { return; } // If element doesn't exist
}
if (target.tagName === 'LI'){
alert(target.id); // Check if the element is a LI
}
});
onclick function from jQuery to pure JS
Seems like you just have far more code than needed.
First, you don't need separate selections to get the dropdownlink
elements. Just include them in the selector.
Then if you need to reference el
, you can just do it directly from the handler. And by using an arrow function, you can also use the this
value present in the Accordion
constructor.
let Accordion = function (el) {
this.el = el;
const dropdownlinks = document.querySelectorAll('.accordion-menu .dropdownlink');
const handler = () => {
this.dropdown(); // You can access the outer `this` value
console.log(this.el);
};
for (const link of dropdownlinks) {
link.onclick = handler
}
};
Hide a div onclick in pure javascript
Use event delegation. Only one click handler is set and works with alerts dynamically added.
document.addEventListener('click', function (event) {
var alertElement = findUpTag(event.target, '.alert');
if (alertElement) {
alertElement.style.display = 'none';
}
});
function findUpTag(el, selector) {
if (el.matches(selector)) {
return el;
}
while (el.parentNode) {
el = el.parentNode;
if (el.matches && el.matches(selector)) {
return el;
}
}
return null;
}
DEMO: http://jsfiddle.net/ht2qp6zj/3/
Is there a pure Javascript way to apply one function to multiple element's events?
You could add the event handler to the parent element, and then determine whether one of the children elements with the desired classname is clicked:
var parent = document.getElementById('parent');
parent.addEventListener('click', function (e) {
if ((' ' + e.target.className + ' ').indexOf(' item ') !== -1) {
// add logic here
console.log(e.target);
}
});
Example Here
or...
var parent = document.getElementById('parent');
parent.addEventListener('click', function (e) {
Array.prototype.forEach.call(parent.querySelectorAll('.item'), function (el) {
if (el === e.target) {
// add logic here
console.log(e.target);
}
});
});
Example Here
The above snippets will only work when you are clicking on the element with the specified class. In other words, it won't work if you click on that given element's child. To work around that, you could use the following:
var parent = document.getElementById('parent');
parent.addEventListener('click', function (e) {
var target = e.target; // Clicked element
while (target && target.parentNode !== parent) {
target = target.parentNode; // If the clicked element isn't a direct child
if (!target) { return; } // If element doesn't exist
}
if ((' ' + target.className + ' ').indexOf(' item ') !== -1){
// add logic here
console.log(target);
}
});
Alternative Example
var parent = document.getElementById('parent');
parent.addEventListener('click', function (e) {
var target = e.target; // Clicked element
while (target && target.parentNode !== parent) {
target = target.parentNode; // If the clicked element isn't a direct child
if (!target) { return; } // If element doesn't exist
}
Array.prototype.forEach.call(parent.querySelectorAll('.item'), function (el) {
if (el === target) {
// add logic here
console.log(target);
}
});
});
Example Here
Remove and replace another onclick function in a div through Pure Javascript?
Consider a sample HTML page:
<html>
<head>
</head>
<body>
<div id ="d1">
<span class="plus childNode1" onclick="expand_collapseChildnodes('childNode1')" id="abc"></span>
</div>
<div id ="d2">
</div>
</body>
</html>
Now to move the element with id abc from DOM element with id d1 to another with id d2
//get the element
var element = document.getElementById("abc");
//detach from source
document.getElementById("d1").removeChild(element);
//remove onclick attribute
element.removeAttribute("onclick");
//add the modified attribute
element.setAttribute("onclick", "sampleFunc()");
//attach the element to another source
document.getElementById("d2").appenChild(element);
Related Topics
Why Doesn't JavaScript Newlines Work Inside HTML
Determine Maximum Possible Div Height
How to Change the Label Size of a Material UI Textfield
Find Unused Images, CSS Rules, Js Script Blocks
Copy All Styles from One Element to Another
How to Know What Elements Are in Current Mouse Position
Fullcalendar.Io: How to Display One Event Per Line in Agendaweek Then Mix All in One
How to Highlight All Occurrences of a Word on a Page with JavaScript or Jquery
Jquery Draggable Event Changing the CSS of Child Element
Is There a Flexible Way to Modify the Contents of an Editable Element
Attribute Onclick="Function()" Not Functioning as Intended
Setting a Whole Style String to an Element from JavaScript (Not Individual Style Parameters)
Does Display:None Keep Elements from Loading
I Need List of All Class Name of Font-Awesome
JavaScript - Changing a Class' Style