click event listener javascript code example

Example 1: javascript onclick event listener

document.getElementById("myBtn").addEventListener("click", function() {
  alert("Hello World!");
});

Example 2: javascript class click event

var elements = document.getElementsByClassName("classname");

var myFunction = function() {
    var attribute = this.getAttribute("data-myattribute");
    alert(attribute);
};

for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', myFunction, false);
}

// If you have ES6 support you can replace your last line with:

    Array.from(elements).forEach(function(element) {
      element.addEventListener('click', myFunction);
    });

Example 3: eventlistener javascript

document.querySelector("button").addEventListener("click", handle);

function handle() {
  alert("I got clicked")
}

Example 4: javascript event listener

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

Example 5: event listener javascript

document.getElementById("myBtn").addEventListener("click", displayDate);

Example 6: addEventListener

<body style="height: 5000px">
 <style>
    body, /* blink currently has bug that requires declaration on `body` */
    html {
      scroll-snap-type: y proximity;
    }
    .snaptarget {
      scroll-snap-align: start;
      position: relative;
      top: 200px;
      height: 200px;
      background-color: green;
    }
 </style>
 <div class="snaptarget"></div>
</body>

Tags:

Java Example