• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Basics / The onclick Event in JavaScript

The onclick Event in JavaScript

The onclick Event in JavaScript

The JavaScript onclick event is triggered when an element is clicked on, such as a button or a link. This event can be used to perform various actions, such as submitting a form, navigating to a new page, or displaying a message.

Here is an example of using the onclick event to submit a form:

<form>
  <label for="name">Name:</label>
  <input type="text" id="name">
  <input type="button" value="Submit" onclick="submitForm()">
</form>
function submitForm() {
  document.forms[0].submit();
}

In this example, the submitForm() function is called when the “Submit” button is clicked. The function then submits the form by calling the submit() method on the first form on the page.

Another example of using onclick event is when you want to navigate to a new page

<a href="#" onclick="goToPage()">Go to page</a>
function goToPage() {
  window.location.href = "http://example.com";
}

In this example, when the user clicks on the “Go to page” link, the goToPage() function is called, and the user will be redirected to “http://example.com”

You can also use onclick event on multiple elements, for example:

<button onclick="changeColor(this)">Change color</button>
<button onclick="changeColor(this)">Change color</button>
function changeColor(el) {
  el.style.backgroundColor = "red";
}

In this example, when the user clicks on any of the buttons, the changeColor() function is called, and the background color of the button that is clicked on will change to red.

It’s important to note that onclick event is supported by all major browsers including Internet Explorer, Google Chrome, and Mozilla Firefox.

Basics

Related Snippets:

  • Bitwise Operators in JavaScript
  • The JavaScript function Math.abs()
  • JavaScript Arrays Explained
  • How To Convert a String to Boolean in JavaScript

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers