Onclick method in html

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.

Источник

GlobalEventHandlers.onclick

Свойство onclick возвращает обработчик события click на текущем элементе.

Примечание: При использовании обработчика события click для вызова любого действия, убедитесь, что событие keydown имеет такое же действие. Это нужно для того, чтобы пользователи, которые не используют мышь или тачскрин могли использовать то же действие.

Синтаксис

element.onclick = functionRef;

где functionRef это функция — зачастую это имя функции, которая объявлена где-то в другом месте или же функциональное выражение. См. «JavaScript Guide:Functions».

Единственный аргумент, переданный в определённую функцию обработчик события это MouseEvent объект. this внутри обработчика будет указывать на элемент, на котором было вызвано событие.

Пример

DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>onclick event exampletitle> script> function initElement()  var p = document.getElementById("foo"); // NOTE: showAlert(); или showAlert(param); так НЕ сработает. // Нужно использовать ссылку на функцию, но не вызов функции. p.onclick = showAlert; >; function showAlert(event)  alert("onclick Event detected!"); > script> style> #foo  border: solid blue 2px; > style> head> body onload="initElement();"> span id="foo">My Event Elementspan> p>click on the above element.p> body> html> 

Или же вы можете использовать анонимную функцию, как здесь:

.onclick = function(event)  alert("moot!"); >; 

Примечания

Событие click возникает, когда пользователь кликает на элемент. Событие click возникнет после событий mousedown и mouseup .

С данным свойством только один обработчик события click может быть назначен объекту. Возможно, вместо данного метода, вам стоит обратить внимание на метод EventTarget.addEventListener() , т.к. он более гибкий и является частью спецификации DOM Events.

Спецификация

Совместимость с браузерами

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 17 окт. 2022 г. by MDN contributors.

Your blueprint for a better internet.

Источник

HTML onclick Event Attribute

The onclick attribute fires on a mouse click on the element.

Browser Support

Syntax

Attribute Values

Technical Details

More Examples

Example

Click on a

element to change its text color to red:

Click me to change my text color.

Example

Click on a button to copy some text from an input field to another input field:

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.

Источник

HTML onclick Attribute

The onclick attribute fires on a mouse click on the element.

Applies to

The onclick attribute is part of the Event Attributes, and can be used on any HTML elements.

Elements Event
All HTML elements onclick

Examples

Button Example

Execute a JavaScript when a button is clicked:

P Example

Click on a

element to change its text color to red:

Click me to change my text color.

Browser Support

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.

Источник

Читайте также:  Hashmap java получить все значения
Оцените статью