as part of my learning process as front end developer, I have decided to produce a product without jQuery and instead use vanilla JavaScript to do all my interactions.
I want to call a function onClick and retrieve the positioning of only the DOM node I clicked which is part of a class. However I don't know how this would be done in pure JavaScript. Basically I want to replicate what $(this) does in jQuery.
Here is my code below so far:
function expand(name) {
var elem = document.querySelectorAll(name)
for (var i = 0; i < elem.length; i++) {
var rect = elem[i].getBoundingClientRect();
console.log(rect.top, rect.right, rect.bottom, rect.left);
}
}
document.querySelectorAll(".box").onclick = expand(this)
Thanks in advance and any other possible solutions to the problem are much appreciated.
document.querySelectorAll
returns a NodeList. This is Array-like and needs to be iterated over
You can use this
inside your handler to refer to the node the handler is attached to
The vanilla way to listen for an event is EventTarget.addEventListener
, this only attaches a handler for one event type at a time so if you want to be able to use multiple you'll need to loop here again (you didn't do this in your example but jQuery lets you do this)
function expand() {
var rect = this.getBoundingClientRect();
console.log(rect.top, rect.right, rect.bottom, rect.left);
}
function nodeListOn(list, type, handler, useCapture) {
var i, t;
type = type.split(/s+/);
for (i = 0; i < list.length; ++i) {
for (t = 0; t < type.length; ++t) {
list[i].addEventListener(type[t], handler, useCapture);
}
}
}
var nodes = document.querySelectorAll('.box');
nodeListOn(nodes, 'click', expand);