Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to use the alert() method in JavaScript ?
Next article icon

How to Use JavaScript: void(0) and onClick?

Last Updated : 12 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Using javascript:void(0) in combination with the onClick attribute is a technique used in HTML to create links or clickable elements that perform actions without navigating away from the page. This is common when you want to attach a JavaScript function or event handler to a clickable element but prevent the default behavior of links (such as following an href).

Explanation:

  • javascript:void(0) is an expression that evaluates to undefined and effectively does nothing. It is used to prevent the default action of the link (<a> element) when clicked.
  • onClick is an HTML attribute that allows you to attach a JavaScript event handler to an element, so a function or block of code is executed when the element is clicked.

Example of Using javascript:void(0) with onClick

HTML
<!DOCTYPE html> <html lang="en"> <head>   <meta charset="UTF-8">   <meta name="viewport" content="width=device-width, initial-scale=1.0">   <title>Using javascript:void(0) with onClick</title> </head> <body>   <!-- Anchor tag using javascript:void(0) with an onClick event -->   <a href="javascript:void(0)" onclick="alert('Link clicked!')">Click me</a>    <script>     function handleClick() {       alert('Button clicked!');     }   </script>    <!-- Button using onClick directly -->   <button onclick="handleClick()">Click this button</button> </body> </html> 

Output:

Screenshot-2024-11-12-123009
Output
Screenshot-2024-11-12-123031
Clicking Button
Screenshot-2024-11-12-123018
Clicking Link

Explanation:

  1. <a href="javascript:void(0)">:
    • href="javascript:void(0)" ensures that clicking the link does not trigger navigation or reload the page.
    • onclick="alert('Link clicked!')" runs a JavaScript function or code when the link is clicked.
  2. onclick Attribute on Button:
    • You can attach JavaScript functions directly to buttons or other elements using the onclick attribute, as demonstrated with the <button> element.

When to Use javascript:void(0):

  • Prevent Default Navigation: It’s often used to prevent <a> tags from following a URL when clicked, allowing you to handle the click event with JavaScript instead.
  • Single Page Applications (SPAs): Frequently used in SPAs where page reloads are generally avoided.

Alternative Approaches:

Instead of using javascript:void(0), you can use # as the href attribute to create a "dummy" link. However, this may cause the page to scroll to the top, so you need to prevent the default behavior explicitly:

HTML
<a href="#" onclick="event.preventDefault(); alert('Link clicked!')">Click me</a> 

Output:

Screenshot-2024-11-12-123226
Output
  • event.preventDefault() prevents the default action (in this case, navigating to the top of the page).

Summary:

  • javascript:void(0) is used to prevent navigation or reloads for clickable elements like links.
  • onclick attaches a JavaScript function or code that runs when the element is clicked.
  • Use these approaches to control the behavior of links and buttons in your web applications

Next Article
How to use the alert() method in JavaScript ?

A

anuragtriarna
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Web QnA

Similar Reads

  • How to toggle a boolean using JavaScript ?
    A boolean value can be toggled in JavaScript by using two approaches which are discussed below: Table of Content Using the logical NOT operatorUsing the ternary operatorUsing the XOR (^) operatorMethod 1: Using the logical NOT operator The logical NOT operator in Boolean algebra is used to negate an
    3 min read
  • How to convert NaN to 0 using JavaScript ?
    NaN (Not a Number) is usually used to indicate an error condition for a function that should return a valid number but it can be converted to 0 using JavaScript. We will discuss how to convert the NaN to 0. Below are the approaches used to convert NaN to 0 using JavaScript: Table of Content Using is
    3 min read
  • JavaScript onclick Event
    The onclick event generally occurs when the user clicks on an element. It's a fundamental event handler in JavaScript, triggering actions or executing functions in response to user interaction, facilitating dynamic and interactive web functionality. In JavaScript, we can use the onclick function in
    2 min read
  • How to use the alert() method in JavaScript ?
    In this article, we will learn how to use the alert() method in JavaScript. The alert() method is used to show an alert box on the browser window with some message or warning. We can use it as a message or as a warning for the user. Approach: To show an alert on the browser window, we make a button.
    2 min read
  • Why Doesn't onclick="this.disabled=true;" Work in JavaScript?
    Using onclick="this.disabled=true;" in JavaScript can sometimes fail because the button's action is triggered before it gets disabled. This means the button's default behavior or associated action may still execute. What Does onclick="this.disabled=true;" Do?This code disables the button immediately
    2 min read
  • What Does javascript:void(0) Mean?
    javascript:void(0) is commonly used in HTML to create a link that doesn’t perform any action or navigate to a new page. When placed in the href attribute of an <a> tag, it allows the link to execute JavaScript code without reloading or changing the current page. This is particularly useful for
    4 min read
  • What is void and when to use void type in JavaScript ?
    In this article, we will know what is void operator in Javascript, along with discussing the particular condition where void operator can be used & understanding their implementation through the examples. The void keyword in JavaScript, is used to evaluate an expression which does not return any
    5 min read
  • How to Open a Popup on Click using JavaScript ?
    Opening a Pop-up when the click action is performed is the user-interactive technique. We can use this functionality in messages, or forms to show some error or alert messages before the user moves to the next action. Table of Content Using display propertyUsing classList PropertyUsing visibility pr
    5 min read
  • How to take user input in JavaScript?
    Interacting with users is the best way to create engaging and dynamic web applications. Taking user input allows your applications to be interactive and responsive. Here we will see the approach to take user input in JavaScript, specifically using the prompt method, which is perfect for beginners. A
    3 min read
  • How to Call a JavaScript Function using an onsubmit Event ?
    HTML has a form element that is used to get the data from the user and send the data to the server. Before the HTML form sends data to the server, it generates an event called "submit". This event can be utilized to execute a JavaScript function that can either validate the form data or notify the u
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences