Is there any way to insert events into the html element at runtime?

Asked

Viewed 417 times

1

Imagine a single page input text, that is, a text field in the HTML document like this: <input value="digite aqui" type="text" id="el"/>.

But I want to insert in this text field, through Javascript, the events onBlur() and onFocus().

The final code would be

<input value="digite aqui" type="text"
    onblur="if(this.value == '') {this.value = 'digite aqui';}" 
    onfocus="if(this.value == 'digite aqui') {this.value = '';}"
    />

This script above is an example of how I wish it to stay, contains parts of the events who would like to make the inclusion the moment they click on a button.

I wanted to include parts within a input existing on the page, no creating this code dynamically.

So catch the onblur="if(this.value == '') {this.value = 'digite aqui';}", along with onfocus="if(this.value == 'digite aqui') {this.value = '';}" and play at <input value="digite aqui" type="text" id="el"/>

Okay, someone proposes an idea of how to do this maneuver?

1 answer

4


You can do it like this:

var input = document.querySelector('input');
var accoes = {
    onblur: "if(this.value == '') {this.value = 'digite aqui';}",
    onfocus: "if(this.value == 'digite aqui') {this.value = '';}"
}
for (var prop in accoes) {
    input.setAttribute(prop, accoes[prop]);
}

Exepmlo: https://jsfiddle.net/8c6j46Lg/

The important part is .setAttribute() that basically changes the HTML as if it were there at the beginning. To make the functionality more organized I created an object to save these rules.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.