Javascript write on click

How to Use JavaScript onclick Events

When writing code in JavaScript, you will often want to execute code when the user interacts with the webpage.

For example, you want to do something when a user clicks a button. You might also want something to happen when a user clicks an image.

How can such functionality be implemented in JavaScript?

You can use the onclick() event, which is a very popular event in JavaScript. It allows you to execute code when a user clicks an element on a webpage (such as a button).

In this article, I will teach you how to use JavaScript onclick events to make your webpages more interactive.

You can skip to a specific section of this JavaScript onclick events tutorial using the table of contents below:

What are JavaScript Events?

There are many different types of events in JavaScript. The onclick is a just one type of JavaScript event.

Events are actions that happen in the web browsern. They can be initiated by the user or by the browser itself.

Some user actions that trigger events include submitting a form, clicking a button, and pressing a key on the keyboard. In this article, we will be focusing on when a user clicks an element.

Developers can make webpages interactive by use of events. You can display a message once a user submits a form, or make a form visible once the user clicks a button.

JavaScript Events are made up of two main components:

When a user presses a key, hovers over an element, or clicks a button, an event is run.

The code that runs when an event starts is the event handler. It is often also called the callback function.

For example, once you click a button, an event handler runs.

An event listener is part of an element such as a button. Its job is to listen, waiting for the user to interact with the element in order to execute the event handler (which, remember, is also called the callback function).

JavaScript onclick Event Main Tips

Here are the main points that you should note as far as the JavaScript onclick event is concerned:

  • The onclick JavaScript event is triggered when the user clicks an element.
  • The onclick event runs a particular line of code when the user clicks an HTML object with the onclick attribute.
  • You can trigger the JavaScript onclick functions using object.onclick .

JavaScript onclick Syntax

To use the JavaScript onclick event, you should specify the object to be affected and indicate the onclick function to be executed.

Here is the syntax for the JavaScript onclick event:

object.onclick = function() script >;

The object can be a button, image, or any other element on the webpage. The function is the name of the function to be called when the element is clicked. The script is the body of the function, specifying what should be done when the function is called.

Changing Text Using JavaScript onclick Events

Suppose you want to change the webpage text when the user clicks a button. The onclick feature can help us implement this.

Let’s first create a webpage with text and a button. We will later create a JavaScript code that will hold the event code.

First, create a new file and give it the name index.html .

Add the following code to the file:

DOCTYPE html> html> head> title>JavaScript onclick Exampletitle> head> body> button>Click Herebutton> p>See JavaScript in Action. p> body> script src="js/onclick.js"> script> html>

The above code creates a basic webpage. The page is considered basic because it does not have any interactive functionality.

When you open the webpage, you will see a button and some text. Nothing will happen if you click the button because we have not added the onclick script function.

Next, let’s consider the tag in the above code.

We have referenced a file named onclick.js stored in a folder named js . The .js extension in the file name indicates that it’s a JavaScript file.

Since the webpage is ready, we can now start to create the onclick event.

However, we should first add the onclick() event listener to our button. This event will begin to listen for when the user clicks the button. So, change the section of the above code to the following:

  

See JavaScript in Action.

We have added the onclick= “changeText()” within the tag.

This adds the onclick listener to the event. The button is now listening, waiting for the user to click it.

When the button is clicked, it will call an event given the name changeText() .

This event will then change the text added within the

tag of the code. But the event itself has not been defined in the index.html file.

We will define it in the onclick.js file.

Remember that we referenced this file within the tag of the code. We can now create the onclick.js file that will hold the code for the changeText() event.

In the same directory where you have stored the index.html file, create a new folder/directory and give it the name js .

Create a new file within this directory, and give it the name onclick.js .

Add the following code to the new file:

const changeText = () =>  const paragraph = document.querySelector("p"); paragraph.textContent = "The changeText() event has changed the Text!" >

We have used the querySelector() method to select the

tag contained in the webpage.

Next, we have used the textContent attribute to specify the text that should be added to the

tag of the webpage. This means that the original text of the

tag will be replaced by the new text.

Now, reload the index.html file on your web browser.

You will see the basic webpage with a button and a text that says, _ See JavaScript in Action.

After you click the button, the text will change to, The changeText() event has changed the Text! .

How to Call a JavaScript Function from an onclick Event

Like most programming languages, JavaScript supports functions. Moreover, it’s possible to call a JavaScript function from an onclick event.

This means that when the element is clicked, the specified function will be called to perform its task. We will demonstrate this by creating a basic webpage with some text and a button.

When the button is clicked, it will call a function that will display an alert box on the webpage. All of this will be done in the HTML file. This means that we will not create a separate JavaScript file.

To start, create a new file and give it the name function.html .

Add the following code to the function:

html> head> script> !-- function hello()  alert("Hello World") > //--> script> head> body> p>JavaScript onclick event will call a function.p> input type="button" onclick="hello()" value="Click Here" /> body> html>

When you open the file on your web browser, it will simply display some text and a button. This time, the button will do something when the user clicks it.

The reason why this button has embedded functionality is that we have added the onclick event to it. This means it’s listening and waiting for when the button is clicked.

The event specifies that when the button is clicked, it should call a function given the name hello() . This function has been defined within the tag of the code.

When the hello() function is called, it will display an alert box on the webpage with the text Hello World .

You have just called a function through the onclick event.

Note that although the JavaScript code was added in the HTML file instead of creating a separate .js file, you can also separate them if you’d like.

How to change the Background Color from an onclick Event

You can use the onclick event to change the background color of the window when it’s clicked.

To demonstrate this, create a new file and give it the name index.html .

Add the following code to the file:

DOCTYPE html> html> head> title>JavaScript onclick title> head> body> p>Click on the screen to change its background color. p> body> script src="js/color.js"> script> html>

The above code creates a simple webpage with a single line of text.

Within the tag of the code, we have referenced a JavaScript file given the name color.js . This is the file that we need to create and add our JavaScript code into. The purpose of this JavaScript code will be to change the color of the window when it is clicked.

Now, in the same directory where you have created the above file, create a new folder/directory and give it the name js .

Insider this folder/directory, create a new file and give it the name color.js .

Add the following code to this file:

 window.onclick = changeColor; function changeColor()  document.getElementsByTagName("BODY")[0].style.backgroundColor = "magenta"; >

In the above JavaScript code, we have added an onclick listener event to the window object.

The window is now listening, waiting for the user to click it. When it’s clicked, it should call a function given the name changeColor() .

The function should change the background color of the tag, which is the entire window, into magenta.

Now, load the index.html file on your web browser. Click the window and see what happens.

The background color of the window should change color to magenta.

Congratulations! You can now see how powerful the JavaScript onclick event is!

In this tutorial, you learned how to work with JavaScript onclick events to build interactive functionality into your webpage.

Here is a brief summary of what you learned in this article:

  • Onclick() is a JavaScript event that executes a particular section of code when an element of the webpage is clicked.
  • It is made up of two components, the event handler and the event listener.
  • The event handler is the code that runs when an event starts.

The event listener listens, waiting for the user to interact with the element in order to execute the event handler.

If you enjoyed this article, be sure to join my Developer Monthly newsletter, where I send out the latest news from the world of Python and JavaScript:

Источник

onclick Event

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

Mouse Events

Event Occurs When
onclick The user clicks on an element
oncontextmenu The user right-clicks on an element
ondblclick The user double-clicks on an element
onmousedown A mouse button is pressed over an element
onmouseenter The pointer is moved onto an element
onmouseleave The pointer is moved out of an element
onmousemove The pointer is moving over an element
onmouseout The mouse pointer moves out of an element
onmouseover The mouse pointer is moved over an element
onmouseup The mouse button is released over an element

See Also:

Tutorial:

Syntax

In JavaScript, using the addEventListener() method:

Technical Details

Bubbles: Yes
Cancelable: Yes
Event type: MouseEvent
Supported
HTML tags:
All exept: , ,
, , , , , , , , and

More Examples

Click a to display the date:

Click a element to change the text color:

Click me to change my color.

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

Click me to change my color.

Click to copy text from one input field to another:

function myFunction() document.getElementById(«field2»).value = document.getElementById(«field1»).value;
>

How to assign an «onclick» event to the window object:

function myFunction() document.getElementsByTagName(«BODY»)[0].style.backgroundColor = «yellow»;
>

Use onclick to create a dropdown:

function myFunction() document.getElementById(«myDropdown»).classList.toggle(«show»);
>

Browser Support

onclick is a DOM Level 2 (2001) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

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:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Php результат выполнения запроса
Оцените статью