onclick handler code example

Example 1: how to add onclick event in javascript

var element = document.getElementById("elem");
element.onclick = function(event) {
  console.log(event);
}

Example 2: onclick="to Function()

<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>


<script>
//Get the button
var mybutton = document.getElementById("myBtn");

// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    mybutton.style.display = "block";
  } else {
    mybutton.style.display = "none";
  }
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}
</script>

Example 3: javascript onclick

document.getElementById("Save").onclick = function ()
    {
     alert("hello");
     //validation code to see State field is mandatory.  
    }

Tags:

Misc Example