{"id":1013,"date":"2026-11-17T11:57:20","date_gmt":"2026-11-17T11:57:20","guid":{"rendered":"https:\/\/gyanipandit.com\/programming\/?p=1013"},"modified":"2026-11-17T11:57:20","modified_gmt":"2026-11-17T11:57:20","slug":"onclick-event-in-javascript","status":"publish","type":"post","link":"https:\/\/gyanipandit.com\/programming\/onclick-event-in-javascript\/","title":{"rendered":"Onclick Event in JavaScript: 3 Ways with Examples"},"content":{"rendered":"<p>Hello friends! Almost every interactive web page starts with one simple thing: something happens when you click. The <strong>click event<\/strong> fires when a user clicks an element: a button, a link, an image, almost anything on the page. It is the most common way to make a web page respond to the user. There are three ways to run JavaScript on a click, and this lesson shows all three, with the one you should normally use. Let&#8217;s begin with the oldest and simplest way.<\/p>\n<h2>1. The onclick HTML Attribute<\/h2>\n<pre class=\"wp-block-code\"><code>&lt;button onclick=\"sayHello()\"&gt;Click me&lt;\/button&gt;\n&lt;p id=\"msg\"&gt;&lt;\/p&gt;\n\n&lt;script&gt;\n  function sayHello() {\n    document.getElementById(\"msg\").textContent = \"Hello, Riya!\";\n  }\n&lt;\/script&gt;<\/code><\/pre>\n<p><strong>Result:<\/strong> when you click the button, the paragraph shows <em>Hello, Riya!<\/em><\/p>\n<p>This is quick for small demos, but it mixes JavaScript into your HTML, which becomes hard to maintain in bigger pages.<\/p>\n<p>There is a cleaner way that keeps JavaScript out of your HTML.<\/p>\n<h2>2. The onclick Property in JavaScript<\/h2>\n<pre class=\"wp-block-code\"><code>&lt;button id=\"btn\"&gt;Click me&lt;\/button&gt;\n\n&lt;script&gt;\n  const btn = document.getElementById(\"btn\");\n  btn.onclick = function () {\n    alert(\"Button clicked!\");\n  };\n&lt;\/script&gt;<\/code><\/pre>\n<p>This keeps HTML and JavaScript separate. The limitation: an element can have only <strong>one<\/strong> <code>onclick<\/code> property. Setting it again replaces the earlier function.<\/p>\n<p>And now the method that professional developers use most of the time.<\/p>\n<h2>3. addEventListener() (Recommended)<\/h2>\n<pre class=\"wp-block-code\"><code>&lt;button id=\"likeBtn\"&gt;\ud83d\udc4d Like&lt;\/button&gt;\n&lt;span id=\"count\"&gt;0&lt;\/span&gt;\n\n&lt;script&gt;\n  const likeBtn = document.getElementById(\"likeBtn\");\n  const countEl = document.getElementById(\"count\");\n  let likes = 0;\n\n  likeBtn.addEventListener(\"click\", () =&gt; {\n    likes++;\n    countEl.textContent = likes;\n  });\n&lt;\/script&gt;<\/code><\/pre>\n<p><strong>Result:<\/strong> each click increases the number next to the button by one.<\/p>\n<p><code>addEventListener()<\/code> lets you attach several handlers to the same element, remove them later with <code>removeEventListener()<\/code>, and control advanced options. Note the event name is <code>\"click\"<\/code>, without &#8220;on&#8221;.<\/p>\n<h2>Using the Event Object<\/h2>\n<p>Here is something many beginners don&#8217;t know. The handler receives an <strong>event object<\/strong> with details about the click:<\/p>\n<pre class=\"wp-block-code\"><code>document.addEventListener(\"click\", (event) =&gt; {\n  console.log(\"You clicked:\", event.target.tagName);\n  console.log(\"Position:\", event.clientX, event.clientY);\n});<\/code><\/pre>\n<p><code>event.target<\/code> is the exact element that was clicked, and <code>clientX<\/code>\/<code>clientY<\/code> give the mouse position.<\/p>\n<h2>Practical Example: Show and Hide an Answer<\/h2>\n<pre class=\"wp-block-code\"><code>&lt;button id=\"toggle\"&gt;Show answer&lt;\/button&gt;\n&lt;p id=\"answer\" hidden&gt;The capital of India is New Delhi.&lt;\/p&gt;\n\n&lt;script&gt;\n  const toggle = document.getElementById(\"toggle\");\n  const answer = document.getElementById(\"answer\");\n\n  toggle.addEventListener(\"click\", () =&gt; {\n    answer.hidden = !answer.hidden;\n    toggle.textContent = answer.hidden ? \"Show answer\" : \"Hide answer\";\n  });\n&lt;\/script&gt;<\/code><\/pre>\n<p>This pattern is used for FAQs, quizzes, menus and &#8220;read more&#8221; buttons.<\/p>\n<h2>Stopping the Default Action<\/h2>\n<p>Clicking a link normally opens it, and clicking a submit button sends a form. Call <code>event.preventDefault()<\/code> to stop that and handle it yourself:<\/p>\n<pre class=\"wp-block-code\"><code>document.getElementById(\"myLink\").addEventListener(\"click\", (event) =&gt; {\n  event.preventDefault();\n  console.log(\"Link click handled by JavaScript instead.\");\n});<\/code><\/pre>\n<h2>Common Mistakes<\/h2>\n<p>Before you start using click events in your own projects, watch out for these mistakes:<\/p>\n<ul>\n<li><strong>Calling the function instead of passing it:<\/strong> <code>btn.onclick = sayHello();<\/code> runs <code>sayHello<\/code> immediately. Write <code>btn.onclick = sayHello;<\/code> (no brackets).<\/li>\n<li><strong>Running the script before the button exists:<\/strong> if your <code>&lt;script&gt;<\/code> is in the <code>&lt;head&gt;<\/code>, <code>getElementById<\/code> returns <code>null<\/code>. Put the script at the end of the body, or use <code>&lt;script defer&gt;<\/code>.<\/li>\n<li><strong>Writing &#8220;onclick&#8221; in addEventListener:<\/strong> it must be <code>\"click\"<\/code>.<\/li>\n<li><strong>Making clickable divs:<\/strong> for accessibility, use a real <code>&lt;button&gt;<\/code> for actions. It works with the keyboard and screen readers automatically.<\/li>\n<\/ul>\n<p>So friends, remember the key difference: <code>onclick<\/code> allows only one handler per element and is overwritten if you set it again, while <code>addEventListener<\/code> allows many handlers and can remove them later. If you need to pass a value to your function, wrap the call in an arrow function, like <code>btn.addEventListener(\"click\", () =&gt; greet(\"Riya\"));<\/code>. And <code>event.target<\/code> is simply the element that was actually clicked. Try the show-and-hide example on your own page, and you will have your first interactive feature ready.<\/p>\n<p>More events: <a href=\"https:\/\/gyanipandit.com\/programming\/events-in-javascript\/\">Events in JavaScript<\/a> \u00b7 <a href=\"https:\/\/gyanipandit.com\/programming\/ondblclick-event-in-javascript\/\">ondblclick<\/a> \u00b7 <a href=\"https:\/\/gyanipandit.com\/programming\/onmouseover-event-in-javascript\/\">onmouseover<\/a> \u00b7 <a href=\"https:\/\/gyanipandit.com\/programming\/arrow-functions-javascript\/\">Arrow functions<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello friends! Almost every interactive web page starts with one simple thing: something happens when you click. The click event fires when a user clicks an element: a button, a link, an image, almost anything on the page. It is the most common way to make a web page respond to the user. There are &#8230; <a title=\"Onclick Event in JavaScript: 3 Ways with Examples\" class=\"read-more\" href=\"https:\/\/gyanipandit.com\/programming\/onclick-event-in-javascript\/\" aria-label=\"Read more about Onclick Event in JavaScript: 3 Ways with Examples\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-1013","post","type-post","status-publish","format-standard","hentry","category-javascript-tutorial","tag-javascript","tag-javascript-tutorial"],"_links":{"self":[{"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/posts\/1013","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/comments?post=1013"}],"version-history":[{"count":4,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/posts\/1013\/revisions"}],"predecessor-version":[{"id":6143,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/posts\/1013\/revisions\/6143"}],"wp:attachment":[{"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/media?parent=1013"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/categories?post=1013"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/gyanipandit.com\/programming\/wp-json\/wp\/v2\/tags?post=1013"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}