- onclick Event
- Mouse Events
- See Also:
- Tutorial:
- Syntax
- Technical Details
- More Examples
- Click me to change my color.
- Click me to change my color.
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Clicking Links With JavaScript
- On Page Load Redirect After Delay
- Message and Link Click When Div Is Tapped
- Tap Div to Click Link (With Message and Delay)
- Uses
- Особенности использования onclick в html
- Навигация по статье:
- Для каких элементов можно использовать атрибут onclick в HTML?
- Особенности применения onclick для ссылки HTML
- Использование функций javascript в атрибуте HTML onclick
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 |
COLOR PICKER
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.
Clicking Links With JavaScript
A user’s tap or mouse click is not always necessary to click a link. A click can be accomplished with JavaScript, too.
There are any number of reasons why JavaScript might be used for clicking. Here are examples.
- Responding to another user action.
- Using the link as an automatic redirector.
- Delay loading the next page upon a normal click or tap on a link.
The essence of the functionality is (1) a link with an id value and (2) JavaScript to click it.
- Example «link with an id value»:
document.getElementById("my-link-element").click();
Below is an example. Three seconds after tapping the div, the browser will load a new page. But first, it will spawn an alert box with a message.
Links can be clicked with JavaScript.
Most of the rest of this article is devoted to the JavaScript click() function in various ways. How to implement the above example will be last — it incorporates functionality I want to present first.
On Page Load Redirect After Delay
Whan a page loads, a countdown begins. When the countdown completes, a link is clicked.
The delay in this example is 5 seconds.
Implementation has two parts.
Here is the link source code. (Every implementation example has this same link source code.)
The link source code’s id value my-link-element is referenced in the JavaScript (below).
Notice that the link source code has no link text or image to tap, although something may be provided. Because the link will be clicked with JavaScript, nothing tappable is required.
Here is the JavaScript code.
When the web page is loaded, the JavaScript immediately sets up a counter for 5 seconds. The counter uses the setTimeout() function. After 5 seconds, function ClickTheLink() is launched.
When launched, function ClickTheLink() clicks the link identified with the my-link-element id value.
The HTML link and the JavaScript optionally may be together in the web page source code. They are separate in these instructions for clarity.
Message and Link Click When Div Is Tapped
When a div is tapped, an alert box with a message is displayed to the page user and then the link is launched.
Implementation has three parts.
Here is the link source code.
The link source code’s id value my-link-element is referenced in the JavaScript (the code is a bit further down).
Notice that the link source code has no link text or image to tap. The link is invisible.
Instead of tapping the link, the person taps somewhere within a div.
Here is the source code of a div to be tapped.
ClickTheLink()" style="cursor:pointer;"> Tap Me!
The CSS style cursor:pointer; is required. You may add any other CSS you wish to style the div.
The onclick color:red; font-weight:bold;»>ClickTheLink() » is required. When the div is tapped, ClickTheLink() launches the JavaScript. The JavaScript presents the message and clicks the link.
Here is the JavaScript code.
Replace MESSAGE with your message.
Optionally, the alert(» MESSAGE «); command in the above JavaScript source code may be replaced in its entirety with custom JavaScript code to do something else entirely.
When the div is tapped, it launches ClickTheLink() , which displays the MESSAGE and clicks the link identified with the my-link-element id value.
The HTML link, the div to click, and the JavaScript optionally may be together in the web page source code.
Tap Div to Click Link (With Message and Delay)
When a div is tapped, a message is spawned and then, after a 3-second delay, a link is clicked.
Implementation has three parts.
Here is the link source code.
The link source code’s id value my-link-element is referenced in the JavaScript (the code is a bit further down).
The link source code has no link text or image to tap. The link is invisible.
Instead of tapping the link, the person taps somewhere within a div.
Here is the source code of a div to be tapped (The div contains the same text as the live example further above.)
MessageAndLaunch()" style="cursor:pointer;"> Tap this div for a message then a delayed new page.
(Use browser "back" icon to return to this page.)
The CSS style cursor:pointer; is required. You may add any other CSS you wish to style the div.
The onclick color:red; font-weight:bold;»>MessageAndLaunch() » is required. The MessageAndLaunch() call is what launches the JavaScript.
Here is the JavaScript code.
When the div is tapped, it launches MessageAndLaunch() . The JavaScript function spawns a message and sets up a countdown of 3 seconds. When the countdown has completed, the link identified with the my-link-element id value is clicked.
The HTML link, the div to click, and the JavaScript optionally may be together in the web page source code. They are separate in these instructions for clarity.
Uses
The above implementation methods with source code may provide ideas for implementing it in other ways.
With a link that has an id value and JavaScript to click the link, your idea may be an easy implementation.
(This article first appeared with an issue of the Possibilities newsletter.)
Was this article helpful to you?
(anonymous form)
Особенности использования onclick в html
Приветствую вас, начинающие веб-разработчики и не только!
Рассмотрим атрибут HTML onclick и его особенности.
Навигация по статье:
onclick— представляет собой атрибут событий, при помощи которого можно задать скрипт срабатывающий при клике на элементе.
Событие onclick является базовым в HTML так как на нем завязано практически всё взаимодействие посетителя с сайтом. Поэтому оно активно применяется в скриптах для реализации определённых задач.
Для каких элементов можно использовать атрибут onclick в HTML?
Синтаксис написание этого атрибута выглядит так:
Давайте разберём что же означает набор этих странных символов.
В данном примере мы задаём атрибут onclick для кнопки button. Чтобы браузер понял что нам нужна именно кнопка мы указываем тип type=»button». Далее в этом атрибуте мы пишем javascript код.
В данном случае мы вызываем модальное окно и выводим в нём текст при помощи метода alert():
В скобках в кавычках указываем текст, который нужно вывести.
И последнее задаём текст, который будет написан на кнопке при помощи value=»Нажми на меня!»
А вот так будет выглядеть это чудо в действии:
Кроме кнопок атрибут onclick можно применять к ссылкам и к любым другим тегам HTML, НО там есть свои особенности, о которых поговорим ниже.
Особенности применения onclick для ссылки HTML
HTML код написания этого атрибута в теге ссылки выглядит так:
Как видите код немного отличается. Дело в том, что по правилам HTML для ссылок нам обязательно нужно указывать атрибут href, в котором нужно указать страницу для перехода. Проблема в том, что нам ведь не нужно чтобы при клике по ссылке осуществлялся переход, нам нужно чтобы срабатывал наш скрипт. Для этого внутри атрибута onclick мы дописываем return false;
Это позволяет нам добиться того чтобы браузер проигнорировал то что написано внутри атрибута href и никуда не переходил.
Вы наверное спросите: «А зачем тогда вообще оставлять атрибут href? Удалили его и все дела!»
В принципе такой вариант тоже возможен и он будет работать, НО с точки зрения валидности HTML кода это не есть хорошо, так как этот атрибут является основным и неотъемлемым для ссылки и удаляя его вы коварно лишаете ссылку важнейшей части её «тела». Валидаторы вам этого не простят!
Внутри атрибута href можно задать следующие значения:
- оставить его пустым href=»»
- поставить в нём решётку href=»#»
- написать href=»javascript://»
- указать реальную ссылку своего сайта href=» //impuls-web.ru/»
Мне больше нравится вариант с javascript:// и #.
Так же артибут onclick можно применять и к любым другим HTML тегам, но это будет скорее из области изощрений и извращений, так как в HTML для событий клика предназначены кнопки и ссылки, поэтому тулить события щелчка к другим тегам как то не очень целесообразно.
Использование функций javascript в атрибуте HTML onclick
Когда к щелчку нужно привязать выполнение нескольких действий javascript лучше использовать функции, а потом вызывать их в атрибуте onclick.
Например, напишем скрипт, который позволит по щелчку на кнопку скрыть один блок и показать другой.