Event handlers in JavaScript

Event Handlers are considered as triggers that execute JavaScript when something happens, such as a click or move of your mouse over a link.
Here I’ll try to provide the proper syntax of some event handlers.
Some are as follows:
  • onClick
  • onFocus
  • onLoad
  • onMouseOver
  • onMouseOut
  • onSelect
  • onUnload
1. onClick
onClick handlers execute something only when the user clicks on buttons, links, and so on.
  1. <script>
  2. function abhi() {
  3. alert("Thank you!")
  4. }
  5. </script>
  6. <form>
  7. <input type="button" value="Click here" onclick="abhi()">
  8. </form>
The function abhi() is invoked when the user clicks the button.
Note: Event handlers are not added inside the <script> tags, but rather, inside the Html tags.
2. onLoad, onunLoad
The onload event handler is used to execute JavaScript after loading.
  1. <body onload="abhi()">
  2. <frameset onload="abhi()">
  3. <img src="abhijeet.gif" onload="abhi()">
The onunload executes JavaScript while someone leaves the page.
  1. <body onunload="alert('Thank you. See you soon')">
3. onMouseOver, onMouseOut
  1. <a href="#" onMouseOver="document.write(‘hello buddy!"> Welcome!</a>
  2. <a href="#" onMouseOut="alert('Be happy!')">Bye Bye!</a>
4. onFocus
  1. <form>
  2. <input onfocus="this.value=''" type="text" value="Your email">
  3. </form>
5. onSelect
The onSelect event fires when the target element has its text selected (highlighted by the user).
Example
  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4. function addmyEvent() {
  5. var ta = document.getElementById('abhi');
  6. abhi.onselect = selectionHandler;
  7. function selectionHandler() {
  8. alert("Its me " + this.id);
  9. }
  10. }
  11. window.onload = addmyEvent;
  12. </script>
  13. </head>
  14. <body>
  15. <textarea id="abhi">Highlight me</textarea>
  16. </body>
  17. </ html >
Output
JavaScript Event handlers
Previous article: Functions in JavaScript