js event listener list code example

Example 1: event listener javascript

const element = document.querySelector(".class__name");

element.addEventListener("click", () => {
	console.log("clicked element");
});

Example 2: event listener javascript

document.querySelector('div').addEventListener('click', () => {
  console.log('div clicked');
});

Example 3: javascript event listener

element.addEventListener("click", function(){ 
   element.innerText = "something"; 
});

Example 4: list listener on a page js

function listAllEventListeners() {
  const allElements = Array.prototype.slice.call(document.querySelectorAll('*'));
  allElements.push(document);
  allElements.push(window);

  const types = [];

  for (let ev in window) {
    if (/^on/.test(ev)) types[types.length] = ev;
  }

  let elements = [];
  for (let i = 0; i < allElements.length; i++) {
    const currentElement = allElements[i];
    for (let j = 0; j < types.length; j++) {
      if (typeof currentElement[types[j]] === 'function') {
        elements.push({
          "node": currentElement,
          "type": types[j],
          "func": currentElement[types[j]].toString(),
        });
      }
    }
  }

  return elements.sort(function(a,b) {
    return a.type.localeCompare(b.type);
  });
}