Javascript click and touch

Topic 9: Standard JavaScript Events Including those for Mobile Devices and Animation and Transition Events

JavaScript Events make it possible for a user to interact with a webpage. Event listeners watch for certain actions to occur, such as a click, touch, mouse movement, etc., and when that event occurs, the listener calls a function that responds to the action.

load

For example, when the webpage loaded, an event listener caused an alert box to open. The event was ‘load’, which fires when the webpage is fully loaded. Here is the code that created the event listener.

Adding Events

There are two ways to add events, as an attribute of an element in the HTML, or with an addEventListener function in the Javascript.

When adding an attribute to the HTML, put ‘on’ in front of the event type and put the function call inside the quotation marks. This is a simple way to add an event listener, but the drawback is you can only add one per element.

When adding a function to the javascript file, you will need to get the element first using getElementById() or similar method. Alternatately, you can omit the element name if you want the event listener to be attached to the whole page, meaning it will fire any time that event happens anywhere on the page.

Add the addEventListener() function, and inside the parenthesis, list the event type in quotes, and the function name. Notice there are no parenthesis after the function name. The benefit to adding an event listener this way is that you can add multiple event listeners to the same element, for instance to deal with both touch and mouse events.

// javascript function
elementName.addEventListener(‘click’, functionName);

Alternately, you could replace the function name with an anonymous function. The drawback of an anonymous function is that you can’t remove the event listener or call it from another place.

Mouse Events

Some events are triggered with the mouse

click

Click is an often used and versitile event listener. The event is fired when a mouse is clicked, the enter button is pushed, or on a touch screen, if the screen is touched. Click is often used with a button, but it can be used with any element, including the whole page.

Click on this paragraph to see the click event listener in action.

dblclick

The doubleclick event fires when the mouse is double-clicked. It isn’t a good idea to use a click and a double-click on the same element, because the click event will fire along with the double-click. Here is an example that uses a dblclick event listener.

mousedown and mouseup

When the user clicks the mouse. It causes 3 events, mousedown, then mouseup, then click.

Читайте также:  Define from variable php

mousedown

Mousedown fires when the mouse button is depressed. It happens before the click event. This mousedown event changes the source of the image.

mouseup

Mouseup fires when the mouse button is released. It also happens before the click event. This mouseup event changes the source of the image back to the original.

Press your mouse button on the kitten to see an example of mousedown and mouseup.

Images purchased from www.thinkstockphoto.com

mouseover and mouseout

Pass your mouse over this element.

This div appears on mouseover, but disappears on mouseout.

mouseover

The mouseover event happens when the mouse pointer passes over the element. This mouseover event adds a class to the div that changes the display property to block.

mouseout

The mouseout event when the pointer moves away from the element. This mouseout event removes the class from the div and the display property reverts to none.

Keyboard Events

Some events are triggered with the keyboard.

click

Click events can be triggered by the enter key on the keyboard. This only works with buttons, inputs, or anchor tags. To make use the enter key, the focus must be on the element to be clicked.

Click the tab key until the button below is in focus (turns blue), then click the enter key to get the time. (You can also click with mouse, or finger on a touch screen.)

keydown, keypress, keyup

When the user clicks a key on the keyboard, it causes 3 events, first keydown, then keypress, and finally when the key is released, keyup.

keydown

When a user presses a key, the keydown event happens. If the key is held down, the event happens repeatedly until the key is released.

keypress

The keypress event happens when the user presses a key, after keydown, but before keyup. Keypress only works for character keys, enter, and delete. It doesn’t work on keys like tab or control.

keyup

The keyup happens when the key is released.

Press any key to see an example of keydown, keypress, and keyup. Keydown will change the background color. Keypress will display what key you pressed, and keyup will change the background-color of the result box below. Notice that if you hold the key down, it will repeatedly fire the keydown and keypress, but the keyup only happens when you release the key. Also notice that keypress will not fire when you push keys like shift, control, tab, etc., but keydown and keyup will.

Touch Events

Some events are triggered by touch when using a touch screen. Since many devices don’t have touch screens, it is smart to add events that can be triggered with the mouse or keyboard in addition to any touch events.

This element shows on touchstart, but disappears on touchend.

It also shows on mouseover for non-touch devices

click

Click events work for touch as well as mouse and keyboard. With touch, the click event is delayed 300ms, which allows the user to do other things, such as zoom or scoll before the click event takes place.

Читайте также:  Java lang nullpointerexception ticking screen

touchstart

The touchstart event happens when the user touches the screen inside an element, creating a touchpoint.

touchmove

The touchmove event happens when the user moves the touchpoint across the screen.

touchend

The touchend event happens when the user removes the touchpoint from the screen.

Here is an example that uses touch events to change the source of the image. Touch the image, then try moving your finger around. It uses touchstart, touchmove, touchend.

var dragArea = document.getElementById(‘dragArea’);
var dragBox = document.getElementById(‘dragBox’);

dragArea.addEventListener(‘touchstart’, function(e) dragBox.src = ‘lion.jpg’;
>);

dragArea.addEventListener(‘touchmove’, function(e) dragBox.src = ‘kittencrouch.jpg’;
>);

dragArea.addEventListener(‘touchend’, function(e) dragBox.src = ‘kitten.jpg’;
>);

touchenter

The touchenter event happens when the user is moving a finger across the screen and moves over an element.

touchleave

The touchleave event happens when the user continues moving across the screen and moves away from the element.

touchcancel

The touchcancel event occurs when the touch is interrupted. This can happen if the finger exits the window of the webpage or if too many fingers touch the screen.

Animation and Transition Events

There are several events that can be used with animations and transitions. They include animationstart, animationiteration, animationend, and transitionend.

animationstart

The animationstart event happens when an animation starts to play for the first time.

animationiteration

The animation iteration event happens when the animation starts to play every time except for the first time.

animationend

The animationend event happens when the last iteration of the animation completes.

To take a look at all three of these events, let’s revisit the rainbow from above. You may have noticed that if you tried to run the animation on the rainbow a second time, it didn’t play. You had to click it a third time to get it to rerun the animation. The reason is that the class to run the animation had already been added, so it needed to be removed before it would run again.

To fix that, you can add an animationend event listener than will remove the class once the animation ends. Here is the code.

dbl.addEventListener(‘animationend’, animationReset);
function animationReset(e) bow.classList.remove(‘rainbow’);
>

An animationend event listener is added which calls a reset function. In the reset function, the rainbow class is removed.

I also added an animationstart event which adds the first cloud, an animationiteration event that adds the other clouds at the beginning of each iteration, and I added to the animationend to remove the clouds when the animation finished.

Copyright © 2018 Tammy Dresen

Источник

touch

Сенсорные экраны отправляют не только событие клика, но и собственное — touch .

Время чтения: меньше 5 мин

Кратко

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

События touch происходят при касании HTML-элемента на тач-экранах. Сюда входит как прикосновение пальцами, так и работа со стилусом. В зависимости от того, какое действие пользователь произвёл (прикоснулся, начал двигать пальцем и так далее) произойдёт то или иное событие touch :

  • touchstart — срабатывает при первом касании
  • touchmove — срабатывает во время движения пальцем по элементу
  • touchend — срабатывает после окончания прикосновения
  • touchcancel — сработает когда событие было прервано

Как пишется

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

Обработчик начала касания по элементу (аналог mousedown ):

 element.addEventListener('touchstart', (event) =>  console.log('Вы приложили палец к элементу')>) element.addEventListener('touchstart', (event) =>  console.log('Вы приложили палец к элементу') >)      

Подписаться на событие, когда пользователь водит пальцем по элементу (аналог mousemove ):

 element.addEventListener('touchmove', (event) =>  console.log('По мне ведут пальцем')>) element.addEventListener('touchmove', (event) =>  console.log('По мне ведут пальцем') >)      

Подписаться на событие, когда пользователь закончил прикосновение (аналог mouseup ):

 element.addEventListener('touchend', (event) =>  console.log('Прикосновение закончено')>) element.addEventListener('touchend', (event) =>  console.log('Прикосновение закончено') >)      

Как понять

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

Когда пользователь работает с компьютером, то чаще всего взаимодействие с элементами на экране происходит с помощью курсора. Для обработки клика нам хватает встроенного события click . Событие click так же работает, если пользователь работает с интерфейсом через смартфон или планшет и взаимодействует с помощью касаний по экрану.

Однако на мобильных устройствах есть не только нажатия, но и жесты, и мультитач. Чтобы дать разработчикам возможность обрабатывать такие сложные действия пользователей, браузеры стали предоставлять низкоуровневые API для обработки touch-событий. С их помощью можно построить интерфейсы с обработкой мультитача и жестов.

Несмотря на то, что события touch очень похожи на click , главное их отличие заключается в поддержке нескольких касаний в разных местах экрана (мультитач). Всего у touch имеется 4 различных события:

  • touchstart — произойдёт, в момент когда пользователь прикоснулся к элементу;
  • touchmove — произойдёт, когда пользователь ведёт пальцем по элементу;
  • touchend — произойдёт, когда пользователь убрал палец с элемента (закончил прикосновение);
  • touchcancel — произойдёт, если событие было прервано, например, если будет слишком много одновременных точек прикосновения либо палец ушёл за пределы элемента или экрана.

Событие касания Touch Event , которое передаётся в обработчик, содержит несколько полезных полей:

  • touches — массив, который содержит объекты всех точек касаний на экране (полезно для обработки мультитач);
  • target Touches — массив, который содержит объекты всех точек касаний на вызываемом элементе.

Рисовалка ниже использует поля события и типы событий касаний. Используйте смартфон, так как касания не работают при использовании мыши.

На практике

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

Егор Огарков советует

Скопировать ссылку «Егор Огарков советует» Скопировано

🛠 Стоит учесть, что браузеры в ответ на некоторые действия пользователя отправляют одновременно и событие click , и событие touch. Например, при прикосновении к элементу (допустим по кнопке) последовательность событий будет следующей:

touchstart → touchend → mousedown → mouseup → click

Стоит помнить эту особенность, если вы на одном и том же элементе делаете обработку этих событий. Если необходимо, чтобы события мыши не возникали на элементе, то в обработчике события касания нужно вызвать prevent Default ( ) :

 element.addEventListener('touchstart', (event) =>  event.preventDefault() // События мыши теперь не будут вызываться>) element.addEventListener('touchstart', (event) =>  event.preventDefault() // События мыши теперь не будут вызываться >)      

🛠 С помощью touch событий можно делать обработку жестов. Например, свайпов. Для этого необходимо будет сохранять координаты, где пользователь прикоснулся (событие touchstart ), и сравнивать с изменением координат во время движения пальца (событие touchmove ). Подробнее можно посмотреть в примере.

Источник

Оцените статью