• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Change onclick action with a Javascript function

I have a button:

When I click this button the first time, I want it to execute Foo (which it does correctly):

What I want to happen when I click the button the first time is to change the onclick function from Foo() to Bar() . Thus far, I've only been able to achieve an infinite loop or no change at all. Bar() would look something like this:

Thus, clicking this button is just alternating which function gets called. How can I get this to work? Alternatively, what's a better way to show/hide the full text of a post? It originally starts shorted, and I provide a button to "see the full text." But when I click that button I want users to be able to click the button again to have the long version of the text go away.

Here's the full code, if it helps:

user66001's user avatar

8 Answers 8

Your code is calling the function and assigning the return value to onClick, also it should be 'onclick'. This is how it should look.

Looking at your other code you probably want to do something like this:

Ryan's user avatar

Otuyh's user avatar

Do not invoke the method when assigning the new onclick handler.

Simply remove the parenthesis:

UPDATE (due to new information ):

Community's user avatar

Thanks to João Paulo Oliveira, this was my solution which includes a variable (which was my goal).

TheSatinKnight's user avatar

I recommend this approach:

Instead of having two click handlers, have only one function with a if-else statement. Let the state of the BUTTON element determine which branch of the if-else statement gets executed:


Live demo: http://jsfiddle.net/simevidas/hPQP9/

Šime Vidas's user avatar

You could try changing the button attribute like this:

Kyle's user avatar

What might be easier, is to have two buttons and show/hide them in your functions. (ie. display:none|block; ) Each button could then have it's own onclick with whatever code you need.

So, at first button1 would be display:block and button2 would be display:none . Then when you click button1 it would switch button2 to be display:block and button1 to be display:none .

Richard Marskell - Drackir's user avatar

For anyone, like me, trying to set a query string on the action and wondering why it's not working-

You cannot set a query string for a GET form submission, but I have found you can for a POST.

For a GET submission you must set the values in hidden inputs e.g.

an action of: "/handleformsubmission?foo=bar" would have be added as the hidden field like: <input type="hidden" name="foo" value="bar" />

This can be done add dynamically in JavaScript as (where clickedButton is the submitted button that was clicked:

See this question for more info submitting a GET form with query string params and hidden params disappear

anotheruser1488182's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged javascript or ask your own question .

Hot Network Questions

change button function javascript

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

JS Reference

Html events, html objects, other references, onclick event.

Call a function when a button is clicked:

More examples below.

Definition and Usage

The onclick event occurs when the user clicks on an HTML element .

Mouse Events

The Mouse Event Object

JavaScript Events

In JavaScript:

In JavaScript, using the addEventListener() method:

Technical Details


More Examples

Click a <button> to display the date:

Click a <h3> element to change the text color:

Another example on how to change the color of an element:

Click to copy text from one input field to another:

How to assign an "onclick" event to the window object:

Use onclick to create a dropdown:

Browser Support

onclick is a DOM Level 2 (2001) feature.

It is fully supported in all browsers:

Get started with your own server with Dynamic Spaces



Get your certification today!

change button function javascript

Get certified by completing a course today!


Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Your Suggestion:

Thank you for helping us.

Your message has been sent to W3Schools.

Top Tutorials

Top references, top examples, web certificates, get certified.

HTML Button onclick – JavaScript Click Event Tutorial

Whenever you visit a website, you'll probably click on something like a link or button.

Links take you to a certain part of the page, another page of the website, or another website entirely. Buttons, on the other hand, are usually manipulated by JavaScript events so they can trigger certain functionality.

In this tutorial, we are going to explore the two different ways of executing click events in JavaScript using two different methods.

First, we'll look at the traditional onclick style that you do right from the HTML page. Then we'll see how the more modern "click" eventListner works, which lets you separate the HTML from the JavaScript.

Here's an Interactive Scrim of HTML Button onclick

How to use the onclick event in javascript.

The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain content on the web page, and other things like that.

You place the JavaScript function you want to execute inside the opening tag of the button.

Basic onclick syntax

For example

Note that the onclick attribute is purely JavaScript. The value it takes, which is the function you want to execute, says it all, as it is invoked right within the opening tag.

In JavaScript, you invoke a function by calling its name, then you put a parenthesis after the function identifier (the name).

onclick event example

I have prepared some basic HTML with a little bit of styling so we can put the onclick event into real-world practice.

And here's the CSS to make it look good, along with all the rest of the example code:


Our aim is to change the color of the text to blue when we click the button. So we need to add an onclick attribute to our button, then write the JavaScript function to change the color.

So we need to make a slight change in our HTML:

The function we want to execute is changeColor() . So we need to write it in a JavaScript file, or in the HTML file inside a <script> tag.

If you want to write your script in a JavaScript file, you need to link it in the HTML using the syntax below:

If you want to write the script in an HTML file, just put it inside the script tag:

Now, let’s write our changeColor() function.

First of all, we need to select the element we want to manipulate, which is the freeCodeCamp text inside the <p> tag.

In JavaScript, you do that with the DOM’s getElementById() , getElementsByClassName() , or the querySelector() methods. Then you store the value in a variable.

In this tutorial, I will be using querySelector() because it is more modern and it's faster. I will also be using const to declare our variables instead of let and var , because with const , things are safer as the variable becomes read-only.

Now that we have the text selected, let's write our function. In JavaScript, the basic function syntax looks like this:

So let’s write our function:

What’s going on?

Remember from the HTML that changeColor() is the function we are going to execute. That’s why our function identifier (name) is set to changeColor . If the name doesn’t correlate with what’s in the HTML, it won’t work.

In the DOM (Document Object Model, refers to all of the HTML), to change anything that relates to style, you need to write “style” then a dot (.). This is followed by what you want to change, which might be the color, background color, font size, and so on.

So, inside our function, we take the name variable we declared to get our freeCodeCamp text, then we change the color to blue.

The color of our the text turns blue any time the button is clicked:

Our code is working!

We could take things a little bit further by changing our text to be more colors:

So, what we want to do is change the text to blue, green, and orange-red.

This time around, the onclick functions in our HTML take the values of the color we want to change the text to. These are called parameters in JavaScript. The function we'll write takes its own too, which we will call “color”.

Our web page changed a little:


So, let's select our freeCodeCamp text and write the function to change its color to blue, green, and orange-red:

How to Use the click eventListener in JavaScript

In JavaScript, there are multiple ways of doing the same thing. As JavaScript itself evolved over time, we started needing to separate the HTML, CSS, and JavaScript code in order to comply with best practices.

Event listeners make this possible as they let you separate the JavaScript from the HTML. You can also do this with onclick, but lets take another approach here.

Heres an interactive scrim about event listeners:

Basic eventlistener syntax.

Now, let's change the freeCodeCampt text to blue by using the click eventListner

This is our new HTML:

And this is what it looks like:


This time around in our script, we need to select the button too (not just the freeCodeCamp text). That’s because there’s nothing JavaScript in the opening tag of our button, which is cool.

So, our script looks like this:

We can also separate our function totally from the eventListener and our functionality will still remain the same:

How to Build a " Show More" and "Show Less" Button with JavaScrpit

One of the best ways to learn is by making projects, so let's take what we've learned about the onclick and "click" eventListner to do build something.

When you visit a blog, you often see excerpts of articles first. Then you can click on a "read more" button to show the rest. Let's try to do that.

This is the HTML we are dealing with:

It’s simple HTML with some facts about freeCodeCamp. And there's a button we already attach an onclick to. The function we want to execute is showMore() , which we will write soon.


It's not super ugly, but we can make it look better and act the way we want it to. So we have some CSS which I will explain below:

What's the CSS doing?

With the universal selector ( * ), we are removing the default margin and padding assigned to elements so we can add our own margin and padding.

We also have box sizing set to border-box so we can include the padding and border in our elements’ total width and height.

We centered everything in the body with Flexbox and gave it a light grey background.

Our <article> element, which contains the text, has a width of 400px , a white background (#fff), and has a padding of 20px at the top, 20 on the left and right, and 0 at the bottom.

The paragraph tags inside of it have a font-size of 18px, and then we gave them a maximum height of 270px . Due to the max height of the article element, all the text won't be contained and will overflow. To fix this, we set overflow to hidden in order not to show that text at first.

The transition property ensures that every change happens after 1 second. All text inside the article are justified and have a margin top of 20 pixels so it doesn’t stay too attached to the top of the page.

Because we removed the default margin, our paragraphs got all pushed together. So we set a bottom margin of 16 pixels in order to separate them from one another.

Our selector, article.open , has a property of max-height set to 1000px . This means that any time the article element has a class of open attached to it, the maximum height will change from 270px to 1000px to show the rest of the article. This is possible with JavaScript – our game changer.

We styled our button with a darkish background and made it white. We set its border to none to remove HTML’s default border on buttons, and we gave it a border radius of 4px so it has a slightly rounded border.

Finally, we used the hover pseudo-class in CSS to change the button cursor to a pointer. The background color slightly changes when a user hovers their cursor over it.

There we go – that’s the CSS.

Our page now looks better:


The next thing we need to do is to write our JavaScript so we can see the rest of the article that is hidden.

We have an onclick attribute inside our button opening tag ready to execute a showMore() function, so let's write the function.

We need to select our article first, because we have to show the rest of it:

The next thing we need to do is write the function showMore() so we can toggle between seeing the rest of the article and hiding it.

What is the function doing?

We use an if…else statement here. This is a crucial part of JavaScript that helps you make decisions in your code if a certain condition is met.

The basic syntax looks like this:

Here, if the class name of the article equals open (that is, we want to add the class of open to it, which was set to a maximum height of 1000px in the CSS), then we want to see the rest of the article. Else, we want the article to return to the initial state where a part of it is hidden.

We do this by assigning it a class of open in the else block, which makes it show the rest of the article. Then we set the class to an empty string (none) in the if block, which makes it return to the initial state.

We can separate the HTML and JavaScript and still use onclick , because onclick is JavaScript. So it's possible to write this in a JavaScript file instead of starting from the HTML.

We can also do this using an eventListner:

Our functionality remains the same!

I hope this tutorial helps you understand how the click event works in JavaScript. We explored two different methods here, so now you can start using them in your coding projects.

Thank you for reading, and keep coding.

Web developer and technical writer focusing on frontend technologies. I also dabble in a lot of other technologies.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started


Change onclick Event of an Element Using JavaScript

Although usually it’s not required but sometimes you may want to change the onClick event of a DOM element using JavaScript. When you click on a Document Object Model (DOM) element, it fires an onclick event. We can capture this event in JavaScript and execute a piece of code. In JavaScript, onclick event expects a function as parameter. This function will be executed when the event occurs. Let’s see how we can change the function to be executed on the fly.

Here is an example link / button code:

Following JavaScript code will capture the onlcik event when a user will click on the button with id “tButton” and call a function called “myFunction”:

The onclick property expects a function and NOT a string –so the following code will not work:

I hope this was of help to you. Please let me know if you have any question about this topic. I will try to help! Thank you for using TechWelkin!

2 thoughts on “Change onclick Event of an Element Using JavaScript”

Clicking on “click me” does nothing. Looking at the page’s source code, I don’t see where the functions are even defined. And it seems to be rather incomplete. I tried to create a webpage using the code shown, and it doesn’t work. What’s missing?

Hi Pete, thanks for the comment. I have updated the code. If you want to execute two different functions in alternating fashion, you may use a toggle variable. If this variable would be set to 1, function abc will execute. And if the variable would be set to 0, function xyz will execute.

Leave a Comment Cancel Reply

Your email address will not be published. Required fields are marked *

Start typing and press enter to search

change button function javascript

How to Set onClick With JavaScript

This tutorial will define the procedure on how to set onClick with JavaScript.

To set the onclick with JavaScript, there are two different methods, which are:

Example 1: Assign a Value to the HTML Element’s onclick Attribute Using JavaScript

In the HTML file, create a heading and a button “ Click me ” with the id “ js ” which will trigger the JavaScript function while clicking on it.

In the following step, the created button will be accessed and an “ onclick ” attribute will be attached to it. Upon the button click, the specified function will be executed and the “ style.backgroundColor ” property will change the button color as follows:

The corresponding output will be:

Example 2: Explicitly Add an Event Listener on the HTML Event

Create a button “ Click here! ” and assigns an id “ event ” to it that will trigger the addEventListener() method on the “click” event:

Fetch the button using its id and then attach an “ addEventListener() ” method by passing a “ click ” event and a function “ eventFunc ” where the background color of the button will be changed:

Example 3: Using All onClick Methods at Once

In this example, the working of all the methods will be displayed at once. First is the default way of adding the onclick attribute within the HTML tag itself. After that, the two methods of setting the onclick attribute with the help of JavaScript have been demonstrated as well.

In the following example, create three buttons and see the functionality of the onclick attribute.

The below function will trigger the “ onclick ” event of the button “ Click ”:

On clicking the “ Click Me ” button, the following function will trigger where a warning message will be displayed.

The given function will trigger the button “ Click here! ”:

The output will display alert messages on each button click:

About the author

change button function javascript

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Oh no! We couldn't find anything like that.

Try another search, and we'll give it our best shot.

How to Use the JavaScript onClick Event: A Step-by-Step Guide

Danielle Ellis

Updated: January 20, 2023

Published: November 23, 2022

If you've ever used a form on a website, chances are you've interacted with JavaScript. It's the technology that makes things like buttons and drop-downs work.  But what is it, and how does it work?

Person on computer learning how to use javascript onclick event

In this post, we're going to take a look at the onClick event in JavaScript . We'll start by explaining what it is and then show you how to use it yourself. After reading this post, you'll be able to add interactivity to your websites using JavaScript.

What is JavaScript onClick event?

JavaScript is a programming language that can be used to add interactivity to websites. The onClick event is one of the most commonly used events in JavaScript. It occurs when an element is clicked on.

For example, say you have a button on your website. When a user clicks that button, you can use the onClick event to do something. Maybe you want to display a message or redirect the user to another page. Whatever the case may be, the onClick event makes it possible.

To use the onClick event, you must add code to your website. Don't worry if you've never coded before - we'll walk you through it step by step.  

How to use an onClick event?

First, you must select the element to which you want to add the onClick event. For our button example, we would use the <button> element.

Next, add an attribute to your element. This attribute is called onClick. This attribute's value is the code you want to run when the element is clicked.

Here's what our code would look like with the onClick event added:

   <button onClick="alert('Hello, world!')">Click me!</button> 

When a user clicks on this button, they will see an alert popup that says, "Hello, world!" You can change the message to anything you want.

You're not limited to just displaying a message, either. You can also use the onClick event to run other javascript code. For example, you could redirect the user to another page using the following code:

   <button onClick="window.location = 'http://www.example.com'">Click me!</button> 

This button would redirect the user to www.example.com when clicked.

As you can see, the onClick event is a powerful way to add interactivity to your website. There are endless possibilities for what you can do with it!  

JavaScript onClick Event Example

Now that we've gone over the basics of the onClick event, let's look at an example.

In this example, we're going to create a button that, when clicked, will change the color of the text on the page. To do this, we'll need to use two things:

The onClick event

The javascript function document.getElementById()

The onClick event will be used to run a function when the button is clicked. The document.getElementById() function will be used to get an element on the page so that we can change its style.

Here's what our code will look like:

See the Pen Untitled by HubSpot ( @hubspot ) on CodePen .

Let's break this down piece by piece.

First, we have our button:

    <button onClick="changeColor()">Click me!</button>

This button has the onClick event added to it. The value of the onClick event is the changeColor() function. This means that when the button is clicked, the changeColor() function will run when the button is clicked.

Next, we have our javascript code:  

   <script>       function changeColor() {          document.getElementById('myText').style.color = 'red';       }    </script>

This is the code that will run when our button is clicked. First, we create a function called changeColor(). This function doesn't take any arguments.

Inside our changeColor() function, we use the document.getElementById() function to get an element on the page. In this case, we're getting the element with the id of "myText".

Once we have our element, we can change its style. In this example, we're changing the color property to red. This will make the text red.

Finally, we have our element:

   <p id="myText">This is some text.</p>

This is a simple paragraph element. The only thing different about this element is that it has an id attribute. The document will use this id attribute.getElementById() function to find the element on the page.

And that's it! When you run this code, you should see a button and some text on the page. When you click the button, the text should turn red.  

Final Tips For Using JavaScript onClick Events

Here are some final tips for using onClick events:

Make sure your code is valid. Invalid code can cause problems with your website. Use a tool like JSLint to check your code for errors.

Test your code in different browsers. Different browsers can interpret code differently. Ensure your code works the way you want it to in all major browsers.

Be careful not to overuse the onClick event. If you use it too much, your website can become overwhelming and confusing for your users. Use it sparingly and only when it makes sense to do so.

That's all there is to know about the onClick event. You can now start using it on your own website.


Don't forget to share this post!

Related articles.

PHP Vs. Node.js, Explained

PHP Vs. Node.js, Explained

Top 20 Node.js Interview Questions for 2023

Top 20 Node.js Interview Questions for 2023

How to Call a Function in JavaScript

How to Call a Function in JavaScript

Node JS: Discover 10+ Courses For Learning To Code With Node JS

Node JS: Discover 10+ Courses For Learning To Code With Node JS

Node Scheduler: Discover How To Leverage It In Your Development Process

Node Scheduler: Discover How To Leverage It In Your Development Process

Best Node.js Books: 15+ Must Have Node JS Books For Any Developer

Best Node.js Books: 15+ Must Have Node JS Books For Any Developer

How To Update Node Versions Using Mac, Windows, and Linux

How To Update Node Versions Using Mac, Windows, and Linux

How to Use the Ternary Operator in JavaScript

How to Use the Ternary Operator in JavaScript

11 Most Popular Node.js CMS Platforms for 2022

11 Most Popular Node.js CMS Platforms for 2022

How to Use the JavaScript Array Splice Method

How to Use the JavaScript Array Splice Method

Learn more about the differences between and uses of these popular programming languages.

To change the text of that button, we can use this code:

You can also type a text here, then click the button above:

If you try to change the text using innerHTML , IE6 will give : "Unknown Runtime Error;" and Netscape 7 simply won't change the text.  So, this code below does not work:
   Let's see an example first:

Button Label

In IE6 and Netscape 7 (I don't know about other browsers), the text can be changed in at least two ways: Using innerHTML property document.getElementById("myButton2"). innnerHTML = "New Button Text using innerHTML"; Try it (this will execute the code above)    Using childNodes property document.getElementById("myButton2"). childNodes[0].nodeValue = "New Button Text using childNodes"; Try it (this will execute the code above)   
Note: The innerHTML method has a problem when run on Netscape 6.2 and 7.02 on the PC (and possibly other versions).  The problem occurs if you try to change the text of a button more than once in the same session (using innerHTML).  For instance, below I change to the innerHTML of the button to a new text: If I subsequently try to change the innerHTML again, the button will get messed up and becomes a small square like this: For this reason, I recommend using the childNodes method instead.
   Here's a function that handles all cases above.  It checks if the button can be changed with the childNodes property first.  If not, then it will try again using the value property.  If that also fails, then it will use the innerHTML property (we use this as the last resort because some Netscape browsers has a problem with it - see above).    <SCRIPT LANGUAGE="JavaScript"> <!-- function replaceButtonText(buttonId, text) { if (document.getElementById) { var button=document.getElementById(buttonId); if (button) { if (button.childNodes[0]) { button.childNodes[0].nodeValue=text; } else if (button.value) { button.value=text; } else //if (button.innerHTML) { button.innerHTML=text; } } } } //--> </SCRIPT> To call this function, pass the ID of the button element ( buttonID ) and the text to put into the button. Example :  replaceButtonText('myButton1', 'new button text'); That will replace the text of the button with the id "myButton" with "new button text".


  1. JavaScript Change Image onclick Event

    change button function javascript

  2. 37 Javascript Change Page On Button Click

    change button function javascript

  3. 34 Change Button Text Onclick Javascript

    change button function javascript

  4. javascript

    change button function javascript

  5. 34 Change Button Name Javascript

    change button function javascript

  6. Add function to button, javascript Code Example

    change button function javascript


  1. How To Make Button Using HTML & CSS #html #css #shorts

  2. JavaScript

  3. °C to °F change function by HTML, CSS and JavaScript #html #css #javascript #shorts

  4. Change Display |change Button Lcd|#lcd

  5. How to display a users text box input when they press a button with JavaScript

  6. চাজিং পোর্ট লাগানোর সঠিক নিয়ম // /Any Android And button phone charging port change//


  1. Change onclick action with a Javascript function

    What might be easier, is to have two buttons and show/hide them in your functions. (ie.

  2. onclick Event

    Call a function when a button is clicked: ... In JavaScript, using the addEventListener() method: object. ... Click a <h3> element to change the text color:.

  3. HTML Button onclick

    The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain

  4. Change onclick Event of an Element Using JavaScript

    Although usually it's not required but sometimes you may want to change the onClick event of a DOM element using JavaScript. When you click on a Document

  5. How to Set onClick With JavaScript

    document.getElementById("js").onclick = function jsFunc ; document.getElementById("event"). ; <button id="html" onclick="htmlFunc()">Click</button><br><br> <

  6. change onclick function of the button dynamically using javascript

    HTML : change onclick function of the button dynamically using javascript [ Beautify Your Computer

  7. How To Change Button Text With JavaScript

    In this tutorial, you'll learn how to change a button's text with JavaScript. Get my free 32 page eBook of JavaScript HowTos

  8. How to Change Button Class in Javascript

    ... you will learn how to change button class in javascript.Source Code:https://www.fwait.com/how-to-change-button-class-in-javascript/My...

  9. How to Use the JavaScript onClick Event: A Step-by-Step Guide

    The onClick event will be used to run a function when the button is clicked. The document.getElementById() function will be used to get an

  10. JavaScript: Changing Button's Text

    <input type="button" value="Button Text" id="myButton1"></input>. To change the text of that button, we can use this code: document.getElementById("myButton1").