Html click and double click

ondblclick Event

The ondblclick event occurs when the user double-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
HTML tags: All HTML elements, EXCEPT: , ,
, , , , , , , , and .
DOM Version: Level 2 Events

Browser Support

ondblclick 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.

Источник

Element: dblclick event

The dblclick event fires when a pointing device button (such as a mouse’s primary button) is double-clicked; that is, when it’s rapidly clicked twice on a single element within a very short span of time.

dblclick fires after two click events (and by extension, after two pairs of mousedown and mouseup events).

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

addEventListener("dblclick", (event) => >); ondblclick = (event) => >; 

Event type

Event properties

This interface also inherits properties of its parents, UIEvent and Event . MouseEvent.altKey Read only Returns true if the alt key was down when the mouse event was fired. MouseEvent.button Read only The button number that was pressed (if applicable) when the mouse event was fired. MouseEvent.buttons Read only The buttons being pressed (if any) when the mouse event was fired. MouseEvent.clientX Read only The X coordinate of the mouse pointer in local (DOM content) coordinates. MouseEvent.clientY Read only The Y coordinate of the mouse pointer in local (DOM content) coordinates. MouseEvent.ctrlKey Read only Returns true if the control key was down when the mouse event was fired. MouseEvent.layerX Non-standard Read only Returns the horizontal coordinate of the event relative to the current layer. MouseEvent.layerY Non-standard Read only Returns the vertical coordinate of the event relative to the current layer. MouseEvent.metaKey Read only Returns true if the meta key was down when the mouse event was fired. MouseEvent.movementX Read only The X coordinate of the mouse pointer relative to the position of the last mousemove event. MouseEvent.movementY Read only The Y coordinate of the mouse pointer relative to the position of the last mousemove event. MouseEvent.offsetX Read only The X coordinate of the mouse pointer relative to the position of the padding edge of the target node. MouseEvent.offsetY Read only The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node. MouseEvent.pageX Read only The X coordinate of the mouse pointer relative to the whole document. MouseEvent.pageY Read only The Y coordinate of the mouse pointer relative to the whole document. MouseEvent.relatedTarget Read only The secondary target for the event, if there is one. MouseEvent.screenX Read only The X coordinate of the mouse pointer in global (screen) coordinates. MouseEvent.screenY Read only The Y coordinate of the mouse pointer in global (screen) coordinates. MouseEvent.shiftKey Read only Returns true if the shift key was down when the mouse event was fired. MouseEvent.mozInputSource Non-standard Read only The type of device that generated the event (one of the MOZ_SOURCE_* constants). This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event). MouseEvent.webkitForce Non-standard Read only The amount of pressure applied when clicking. MouseEvent.x Read only Alias for MouseEvent.clientX . MouseEvent.y Read only Alias for MouseEvent.clientY .

Examples

JavaScript

const card = document.querySelector("aside"); card.addEventListener("dblclick", (e) =>  card.classList.toggle("large"); >); 

HTML

aside> h3>My Cardh3> p>Double click to resize this object.p> aside> 

CSS

aside  background: #fe9; border-radius: 1em; display: inline-block; padding: 1em; transform: scale(0.9); transform-origin: 0 0; transition: transform 0.6s; user-select: none; > .large  transform: scale(1.3); > 

Result

Specifications

Источник

Bind Different Events to Click and Double Click

You might want a link to have a special action when double-clicked which prevents the default action of the link (go to another page). So: Double-click: does something special, does not do normal click event at all
Click: works as normal You’ll need to have a very slight delay on firing off the normal click action, which you cancel when the double click event happens.

function doClickAction() < $("#click h2").append("•"); >function doDoubleClickAction() < $("#double-click h2").append("•"); >var timer = 0; var delay = 200; var prevent = false; $("#target") .on("click", function() < timer = setTimeout(function() < if (!prevent) < doClickAction(); >prevent = false; >, delay); >) .on("dblclick", function() < clearTimeout(timer); prevent = true; doDoubleClickAction(); >);

Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.

Comments

This script obviously fails if your OS dblclick threshold is higher than 200ms (and mostly is). Just click again after the “click” dot appears – most probably “double click” dot will be added, that’s because your script already finished the timer but OS is still of course considering the second one as double click but has nothing to cancel.
The right solution is to have single click event handler and check whether you have running timer – if so, cancel it and do double click action. The finished timer itself will do single click actions.

Here’s a solution to enable double clicking, but not requiring JQuery’s dblclick method. It only uses click.

var timer = 0; var delay = 200; var clicked = false; $('#target') .click (function () < var sel = this; if (clicked) < clearTimeout (timer); doDoubleClickAction(); // aha! clicked = false; >else < clicked = true; timer = setTimeout (function () < doSingleClickAction(); clicked = false; >, delay); > // end if (clicked) >); 

It doesn’t work for me because it is executed as follows:
Two rapid clicks (intended as a double click) => the click event handler is executed twice, then the double click event is executed once. So setTimeout is executed twice in the click event handler, thus ‘timer’ refers to the second timeout object. This second object is cleared by the double click event, but the first timeout object is not cleared. As a result we have double click executed once, then the first single click is executed once. As a solution, in the single click event handler, before creating timer = setTimeout(…) , I do a clearTimeout(timer). Then it works as intended.

You need a mix of timeout and event.detail checks to make it work.
Check my answer on stackoverflow – https://stackoverflow.com/a/60177326/670839

It’s a good idea but when the time between 2 clicks is in range of 201ms to 500ms then both actions will be called, because time out between 2 clicks to trigger a dbclick event is 500ms (default in Window OS), so this solution is not work well in all cases.
My solution to fix this bug:

const mouseTestElement = document.querySelector("#click-area"); let timeOutFunction = null; let countClick = 0; const TIME_OUT = 200; mouseTestElement.addEventListener('click', (event) => < clearTimeout(timeOutFunction) countClick++; timeOutFunction = setTimeout(() => < if (countClick === 1) < // handle for single click console.log('Single click') >else if (countClick === 2) < // handle for double click console.log('Double click') >countClick = 0; >, TIME_OUT) >); 

Источник

dblclick

Это незавершённая статья. Вы можете помочь её закончить! Почитайте о том, как контрибьютить в Доку.

Кратко

Скопировать ссылку «Кратко» Скопировано

Событие двойного клика на HTML-элементе происходит, когда пользователь в течение короткого времени дважды кликает один элемент. Временной промежуток между кликами должен быть небольшим, иначе браузер интерпретирует его не как dblclick , а как несколько отдельных click событий.

Как пишется

Скопировать ссылку «Как пишется» Скопировано

На событие dblclick можно подписаться и информировать пользователя, например:

 document.addEventListener('dblclick', event =>  alert('На странице зафиксирован двойной клик!')>) document.addEventListener('dblclick', event =>  alert('На странице зафиксирован двойной клик!') >)      

Также можно отслеживать двойные клики по любым элементам на странице:

 const card = document.querySelector('.card') // установим обработчик на событие двойного кликаcard.addEventListener('dblclick', function ()  alert('Вы дважды кликнули по карточке!')>) const card = document.querySelector('.card') // установим обработчик на событие двойного клика card.addEventListener('dblclick', function ()  alert('Вы дважды кликнули по карточке!') >)      

В функцию-обработчик можно передать объект события, который содержит поля с информацией о клике, например:

Чтобы получить доступ к объекту события, функция-обработчик должна принимать его в качестве параметра:

 card.addEventListener('dblclick', function (event)  alert(event.target.classList) // отображает название класса элемента, по которому дважды кликнули>) card.addEventListener('dblclick', function (event)  alert(event.target.classList) // отображает название класса элемента, по которому дважды кликнули >)      

В примере ниже двойной клик по карточке меняет её размер:

 const card = document.querySelector('.card') card.addEventListener('dblclick', function ()  card.classList.toggle('card_enlarged') // модификатор увеличивает размер карточки>) const card = document.querySelector('.card') card.addEventListener('dblclick', function ()  card.classList.toggle('card_enlarged') // модификатор увеличивает размер карточки >)      

Источник

HTML ondblclick Event Attribute

Execute a JavaScript when a button is double-clicked:

Definition and Usage

The ondblclick attribute fires on a mouse double-click on the element.

Browser Support

Syntax

Attribute Values

Technical Details

More Examples

Example

Double-click on a

element to change its text color to red:

Double-click me to change my text color.

Example

Double-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
Оцените статью