- How to Make Button onclick in HTML
- How to add URL to the window object
- Example of adding URL to the window object:
- Example of using a button onclick to know the current date:
- Example of adding an onclick event:
- HTML onclick Event Attribute
- Browser Support
- Syntax
- Attribute Values
- Technical Details
- More Examples
- Example
- Example
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Событие нажатие на кнопку html
- Использование кнопок
- Простая кнопка
- Добавление сочетаний клавиш на кнопки
- Выключенные / Включённые кнопки
- Валидация
- Примеры
- Спецификации
- Browser compatibility
How to Make Button onclick in HTML
The onclick attribute is an event attribute that is supported by all browsers. It appears when the user clicks on a button element. If you want to make a button onclick, you need to add the onclick event attribute to the element.
How to add URL to the window object
The button onclick runs a script when the user clicks a button. Let’s see an example where we have a button, clicking on which you’ll go to our website. To achieve this, we’ll just add the URL of the website to the window object.
Example of adding URL to the window object:
html> html> head> title>Title of the document title> head> body> button onclick="window.location.href='https://w3docs.com';">Click Here button> body> html>
You can also use a button onclick in order to know the current date just by adding «getElementById(‘demo’).innerHTML=Date()» to the onclick event.
Example of using a button onclick to know the current date:
html> html> head> title>Title of the document title> head> body> p>Click the button to see the current date. p> button onclick="getElementById('demo').innerHTML=Date()">What day is today? button> p id="demo"> p> body> html>
The onclick event is used to call a function when an element is clicked. That is why it is mostly used with the JavaScript function. Let’s consider an example where you need to click the button to set a function that will output a message in a element with id=»demo».
Example of adding an onclick event:
html> html> head> title>Title of the document title> head> body> p>There is a hidden message for you. Click to see it. p> button onclick="myFunction()">Click me! button> p id="demo"> p> script> function myFunction( ) < document.getElementById("demo").innerHTML = "Hello Dear Visitor! We are happy that you've chosen our website to learn programming languages. We're sure you'll become one of the best programmers in your country. Good luck to you!"; > script> body> html>
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:
Related Pages
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.
Событие нажатие на кнопку html
Атрибут значения элементов elements’ value содержит строку DOMString , которая используется в качестве метки кнопки.
input type="button" value="Нажми на меня">
Если вы не укажете value , вы получите пустую кнопку:
Использование кнопок
Элементы не имеют поведения по умолчанию (их двоюродные братья, (en-US) и (en-US) используются для отправки и сброса форм соответственно). Чтобы кнопки делали что-либо, вы должны написать код JavaScript для выполнения работы.
Простая кнопка
Мы начнём с создания простой кнопки с обработчиком события click (en-US) , который запускает наш компьютер (ну, он переключает value кнопки и текстовое содержимое следующего абзаца):
form> input type="button" value="Запустить ПК"> form> p>ПК выключен.p>
const button = document.querySelector('input'); const paragraph = document.querySelector('p'); button.addEventListener('click', updateButton); function updateButton() if (button.value === 'Запустить ПК') button.value = 'Выключить ПК'; paragraph.textContent = 'ПК запущен!'; > else button.value = 'Запустить ПК'; paragraph.textContent = 'ПК выключен.'; > >
Сценарий получает ссылку на объект HTMLInputElement , представляющий в DOM, сохраняя этот параметр в переменной button . Затем addEventListener() используется для установки функции, которая будет запускаться, когда на кнопке происходят события click (en-US) .
Добавление сочетаний клавиш на кнопки
Сочетания клавиш, также известные как клавиши доступа и их эквиваленты на клавиатуре, позволяют пользователю активировать кнопку с помощью клавиши или комбинации клавиш на клавиатуре. Чтобы добавить сочетание клавиш к кнопке — точно так же, как вы сделали бы с любым , для которого это имеет смысл, — вы используете глобальный атрибут accesskey .
В этом примере, s это специфичная клавиша доступа (ты должен нажать s плюс конкретные клавиши-модификаторы для вашей комбинации браузера и операционной системы; вы можете увидеть полный список на странице accesskey).
form> input type="button" value="Включить ПК" accesskey="s"> form> p>ПК выключен.p>
const button = document.querySelector('input'); const paragraph = document.querySelector('p'); button.addEventListener('click', updateButton); function updateButton() if (button.value === 'Включить ПК') button.value = 'Выключить пк'; paragraph.textContent = 'ПК включён!'; > else button.value = 'Включить ПК'; paragraph.textContent = 'ПК выключен.'; > >
Примечание: Проблема с приведенным выше примером, конечно, заключается в том, что пользователь не будет знать, что такое ключ доступа! На реальном сайте вам пришлось бы предоставлять эту информацию таким образом, чтобы это не противоречило дизайну сайта (например, путем предоставления легкодоступной ссылки, которая указывает на информацию о том, что такое ключи доступа к сайту).
Выключенные / Включённые кнопки
Чтобы выключить кнопку необходимо просто добавить на неё глобальный атрибут disabled , вот так:
input type="button" value="Я выключена" disabled>
Вы можете включать и отключать кнопки во время выполнения, просто установив disabled вместо true или false . В этом примере наша кнопка изначально включена, но если вы нажмете ее, она будет отключена с помощью button.disabled = true . А setTimeout() затем функция используется для возврата кнопки обратно в ее включённое состояние через две секунды.
input type="button" value="Enabled">
const button = document.querySelector('input'); button.addEventListener('click', disableButton); function disableButton() button.disabled = true; button.value = 'Выключена'; window.setTimeout(function() button.disabled = false; button.value = 'Включена'; >, 2000); >
Если атрибут disabled не указан, то кнопка наследует своё disabled состояние из своего родительского элемента. Это позволяет включать и отключать группы элементов одновременно, заключая их в контейнер, такой как элемет, и затем установить disabled на контейнер.
Приведенный ниже пример показывает это в действии. Это очень похоже на предыдущий пример, за исключением того, что атрибут disabled устанавливается в при нажатии первой кнопки — это приводит к отключению всех трех кнопок до истечения двухсекундного тайм-аута.
fieldset> legend>Button grouplegend> input type="button" value="Button 1"> input type="button" value="Button 2"> input type="button" value="Button 3"> fieldset>
const button = document.querySelector('input'); const fieldset = document.querySelector('fieldset'); button.addEventListener('click', disableButton); function disableButton() fieldset.disabled = true; window.setTimeout(function() fieldset.disabled = false; >, 2000); >
Примечание: Firefox, в отличие от других браузеров, по умолчанию сохраняет динамическое отключенние состояния из одного при загрузке разных страниц. Используйте атрибут autocomplete для управления этой функцией.
Валидация
Кнопки не участвуют в проверке валидации; они не имеют реальной ценности для валидации.
Примеры
div class="toolbar"> input type="color" aria-label="select pen color"> input type="range" min="2" max="50" value="30" aria-label="select pen size">span class="output">30span> input type="button" value="Clear canvas"> div> canvas class="myCanvas"> p>Добавьте подходящий фолбэк здесь.p> canvas>
body background: #ccc; margin: 0; overflow: hidden; > .toolbar background: #ccc; width: 150px; height: 75px; padding: 5px; > input[type="color"], input[type="button"] width: 90%; margin: 0 auto; display: block; > input[type="range"] width: 70%; > span position: relative; bottom: 5px; >
let canvas = document.querySelector('.myCanvas'); let width = canvas.width = window.innerWidth; let height = canvas.height = window.innerHeight-85; let ctx = canvas.getContext('2d'); ctx.fillStyle = 'rgb(0,0,0)'; ctx.fillRect(0,0,width,height); let colorPicker = document.querySelector('input[type="color"]'); let sizePicker = document.querySelector('input[type="range"]'); let output = document.querySelector('.output'); let clearBtn = document.querySelector('input[type="button"]'); // covert degrees to radians function degToRad(degrees) return degrees * Math.PI / 180; >; // update sizepicker output value sizePicker.oninput = function() output.textContent = sizePicker.value; > // store mouse pointer coordinates, and whether the button is pressed let curX; let curY; let pressed = false; // update mouse pointer coordinates document.onmousemove = function(e) curX = (window.Event) ? e.pageX : e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); curY = (window.Event) ? e.pageY : e.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); > canvas.onmousedown = function() pressed = true; >; canvas.onmouseup = function() pressed = false; > clearBtn.onclick = function() ctx.fillStyle = 'rgb(0,0,0)'; ctx.fillRect(0,0,width,height); > function draw() if(pressed) ctx.fillStyle = colorPicker.value; ctx.beginPath(); ctx.arc(curX, curY-85, sizePicker.value, degToRad(0), degToRad(360), false); ctx.fill(); > requestAnimationFrame(draw); > draw();
Спецификации
Browser compatibility
BCD tables only load in the browser