Is there a way to insert events in the html element at runtime?

1

Imagine a page with a single 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 the events onBlur() and onFocus() into this text field.

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 want it to be, it contains parts of events that I would like to include as soon as I click a button.

I wanted to include parts within a input already on the page, nothing to create this code dynamically.

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

Okay, does anyone propose an idea how to do this maneuver?

    
asked by anonymous 02.07.2016 / 10:17

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: link

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

    
02.07.2016 / 10:21