Javascript addeventlistener text input

Метод addEventListener

Метод addEventListener позволяет назначить на элемент обработчики событий. С его помощью, можно указать, например, что делать при клике по кнопке или что делать при наборе текста в текстовом поле. В первом параметре указываем тип передаваемого события, во втором — функцию, которая будет срабатывать после события, указанного в первом параметре. В третьем необязательном параметре передаем характеристики объекта ( once , capture , passive ) или параметр useCapture .

Синтаксис

элемент.addEventListener(‘тип события’, функция, [характеристики объекта]); или элемент.addEventListener(‘тип события’, функция, [useCapture]);

Пример

Давайте сделаем так, чтобы при клике на кнопку выводилось сообщение:

Пример

Давайте напишем код, чтобы при потере фокуса в инпуте выводилось сообщение с текстом этого инпута:

Пример

Давайте сделаем так, чтобы при клике на кнопку сообщение выводилось в консоль только один раз. Для этого воспользуемся вторым параметром:

Пример

Параметр passive запрещает вызывать метод event.preventDefault при обработке события. Давайте к предыдущему примеру применим метод event.preventDefault , а также укажем в параметре passive значение true :

После выполнения кода мы увидим следующие сообщения:

Пример

Параметр useCapture в значении true показывает всплытие событий от внутреннего элемента до внешнего, при значении false — от внешнего до внутреннего элемента. При передаче параметра useCapture его имя опускается и записывает просто true или false . Давайте посмотрим как всплывают события в родительском и дочернем элементах при клике на них:

Parent

Child

#parent < width: 60px; padding: 10px; border: 1px solid red; text-align: center; >#child < width: 60px; marging-right: 40px; border: 1px solid blue; text-align: center; >let parent = document.querySelector(‘#parent’); let child = document.querySelector(‘#parent’); parent.addEventListener(‘click’, () => alert(‘parent’), true ); child.addEventListener(‘click’, () => alert(‘child’), true );

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

Источник

How to add Javascript addEventListener on BrowserEvent

The Javascript addEventListener allows us to attach an event listener to the document or a DOM element that fires whenever an event occurs. This is the best approach for handling events in Javascript, as in the old times we use to add an inline event on elements.

In this article, we’ll learn how to use addEventListener, what are different events we can use, and at last, demonstrate a few examples of addEventListener.

What is Javascirpt addEventListener

Every time when a user, interacts with a DOM element, like a keypress, mouse move, scroll, and more, that time event is fire. An event can happen because of user interaction or generated by API to represent the progress of an asynchronous task.

We can attach and register an event handler to an HTML element like button, span, input, and div by using addEventListener. Events are normally used in association with functions or handlers and the function will not be executed before the event occurs (such as when a user presses a key).

Читайте также:  Java hibernate jpa spring

We can think addEventListener is the replacement for the old approach of the event handler attribute and it recommends the approach to handling an event. We can add multiple handlers for the same event.

Event handlers
To react to events we can assign a handler – a function that runs in case of an event. Handlers is a way to run JavaScript code in case of user actions. There are several ways to assign a handler. Let’s see them, starting from the simplest one.

HTML-attribute
A handler can be set in HTML with an attribute named on.

addEventListener
The EventTarget.addEventListener() method adds the specified EventListener-compatible object to the list of event listeners for the specified event type on the EventTarget on which it is called. The event target may be an element in a document, the Document itself, a Window, or any other object that supports events (such as XMLHttpRequest).

const button = document.getElementById('add'); button.addEventListener('click', ev => 

Syntax of Javascript addEventListener

Each DOM event is represented by an object that is based on the Event interface. Information contained in each event object is different based on event types.

targetElement.addEventListener(eventType, listener); targetElement.addEventListener(eventType, listener, options); targetElement.addEventListener(eventType, listener, useCapture);
  1. eventType: Is a type of event, in Javascript we have lots of event types like click, blur, and mousemove.
  2. listener: It serves as a listener for the event and handler function which is called in response to the event that occurs.
  3. useCapture: This is an optional value for controlling event propagation. By default is false for the bubbling phase and true for capturing phase.
  4. options Optional, An options object that specifies the characteristics of the event listener.

Example of Javascript addeventlistener click

Let’s demonstrate the addEventListener click example, here is a screenshot of our example.

In this example, we add the event listener to the following elements.

  • Javascript adds an event listener on Add button to increment the num value.
  • Javascript adds even listener on Subtract button to decrement num value.
  • Javascript onload eventListener on window object to initialize num value to zero.

We have used the getElementById method to get references on buttons and p tag so that we can listen to events and assign value to the paragraph tag. The add button will increment the num value, subtract button will decrement the num value by clicking the event and assigning the num value to the paragraph tag with id=”number”.

      

Javascript addEventListener click

Number : id="number">

id="addBtn">Add

Javascript mouseover and mouseout Example of Javascript addEventListener

In our second example, we’ll addEventListener of mouseover and mouseout over a section tags. When the user moves the mouse over the section tag it will add a background yellow and mouseout event will add white background. Here is a screenshot of the javascript mouseover and mouseout events.

Javascript mouseover and mouseout event

    section 
Javascript mouse EventListener

Mouseover and mouseout event

Javascript addEventListener input event

In our last example, we’ll demonstrate the input event on input text by adding addEventListener. Whatever user type on input, we can listen to this event and we have taken its value and assigned it to the innerHTML of a paragraph element.

Javascript addEventListener

Javascript input event

    

Javascript input EventListener

=

On our input event, the second argument event is the event object of input, to get the input value that we have typed, and can get from the event.target.value.

Javascript addEventListener types

We had demonstrated only three examples, Javascript has lots of events and here we had listed a few based on its types. We can classify this event based on its type and here we had listed some of them to learn more about events then check this link.

Javascript mouse events

  1. click – when the mouse clicks on an element (touchscreen devices generate it on a tap).
  2. contextmenu – when the mouse right-clicks on an element.
  3. mouseover / mouseout – when the mouse cursor comes over / leaves an element.
  4. mousedown / mouseup – when the mouse button is pressed/released over an element.
  5. mousemove – when the mouse is moved.

Javascript Form element events

Here we had listed some of the most common events on forms.

  1. submit – when the visitor submits a .
  2. focus – when the visitor focuses on an element, e.g. on a .

Javascript Keyboard events

  1. keydown When a user pushes a keyboard key.
  2. keyup – When a user presses and releases a key.
  3. keypress – The keypress event is fired when a key that produces a character value is pressed down.

Related posts

Источник

Pure JavaScript listen to input value change

Is there a way I can create a constant function that listens to an input, so when that the input value changes, something is triggered immediately? I am looking for something using pure JavaScript, no plugins, no frameworks and I can’t edit the HTML. Something like, for example: When I change the value in the input MyObject , this function runs.

11 Answers 11

HTMLInputElementObject.addEventListener('input', function (evt) < something(this.value); >); 

Note that typeof this.value is string . If a number is needed, convert it with parseInt or parseFloat.

In continuation to @ImShogun ‘s remark. Check Azune-NK’s answer to see how to trigger the event from JavaScript, if you change the value there. Super helpful.

@ImShogun This answer seems to be able to watch properties of elements such as value: stackoverflow.com/a/61975440/1764521

/* Event listener */ document.getElementsByName("Thing")[0].addEventListener('change', doThing); /* Function */ function doThing()

And as the others pointed out, doesn’t trigger until you exit the input field either. Old answer by now, I know. But these answers pop up surprisingly often and they never mention the limitations.

@ImShogun This answer seems to be able to watch properties of elements such as value: stackoverflow.com/a/61975440/1764521

Actually, the ticked answer is exactly right, but the answer can be in ES6 shape:

HTMLInputElementObject.oninput = () => < console.log('run'); // Do something >

Or can be written like below:

HTMLInputElementObject.addEventListener('input', (evt) => < console.log('run'); // Do something >); 
el.addEventListener('input', function () < fn(); >); 

But, if you want to fire event when you change inputs value manually via JavaScript you should use custom event (any name, like ‘myEvent’, ‘ev’, etc.). If you need to listen to forms ‘change’ or ‘input’ event and you change inputs value via JavaScript, you can name your custom event ‘change’ or ‘input’, and it will work too.

var event = new Event('input'); el.addEventListener('input', function () < fn(); >); form.addEventListener('input', function () < anotherFn(); >); el.value = 'something'; el.dispatchEvent(event); 

This is it! Thank you. That element.dispatchEvent(new Event(‘change’)) was key. Didn’t make sense that event isn’t triggered on manual JS change, but suddenly it does. Colour me stupid.

Another approach in 2021 could be using document.querySelector() :

const myInput = document.querySelector('input[name="exampleInput"]'); myInput.addEventListener("change", (e) => < // here we do something >); 

HTML form input contain many events. Refer from HTMLElement, on the sidebar go to Events menu and expand it. You will see many useful events, such as beforeinput , change , copy , cut , input , paste , and drag drop events.

iput & change

The beforeinput , and input events are fired by order when you type the form input value.

When the form input value has changed and you lost focus on that input, the change event is fired.

Cut, copy, and paste

When you cut ( CTRL + X on keyboard shortcut) the input value, the cut , beforeinput , input events are fired. When you copy (CTRL+C on keyboard shortcut), the copy event is fired alone.

When you paste the value from the clipboard ( Ctrl + V on the keyboard shortcut), the paste , beforeinput , input events are fired.

JavaScript change value

To change the input value by JavaScript and make important events work, you need to dispatch at least two events by order. One is input and two is change . So that you can focus your code to listened to input or change event. It’s easier this way.

Here is all the sample code.

(() => < let inputText = document.getElementById('text'); let submitBtn = document.getElementById('submit'); let triggerJSBtn = document.getElementById('button'); submitBtn.addEventListener('click', (event) =>< event.preventDefault(); // just prevent form submitted. >); triggerJSBtn.addEventListener('click', (event) => < const thisTarget = event.target; event.preventDefault(); inputText.value = thisTarget.innerText; inputText.dispatchEvent(new Event('input')); inputText.dispatchEvent(new Event('change')); >); inputText.addEventListener('beforeinput', (event) => < const thisTarget = event.target; console.log('beforeinput event. (%s)', thisTarget.value); >); inputText.addEventListener('input', (event) => < const thisTarget = event.target; console.log('input event. (%s)', thisTarget.value); >); inputText.addEventListener('change', (event) => < const thisTarget = event.target; console.log('change event. (%s)', thisTarget.value); >); inputText.addEventListener('cut', (event) => < const thisTarget = event.target; console.log('cut event. (%s)', thisTarget.value); >); inputText.addEventListener('copy', (event) => < const thisTarget = event.target; console.log('copy event. (%s)', thisTarget.value); >); inputText.addEventListener('paste', (event) => < const thisTarget = event.target; console.log('paste event. (%s)', thisTarget.value); >); >)();
/* For beautification only */ code < color: rgb(200, 140, 50); >small
 

Text:

Text 2:
(For lost focus after modified first input text so the change event will be triggered.)

Press F12 to view results in your browser console.

Please press F12 to open the browser’s console and see the result there.

Источник

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