How to add an onBlur event without overwriting the original?

Asked

Viewed 5,368 times

5


I have a code that’s basically like this:

<input type="text" value="" onfocus="myFunction(this);" onblur="alert('1');">

<script>
  function myFunction(obj) {
    obj.onblur = function() {
      alert("2");
    };
  }
</script>

How can I do to run the original onBlur event after the event added by my function?

This here is the link to my full function, so you can better understand my problem: http://jsbin.com/zedot/2/watch?html,js,output

3 answers

5


Solution #1 (recommended): addEventListener

With addEventListener you can associate so many Event handlers an element as many as necessary:

obj.addEventListener('blur', function() {
    alert("2");
}, false);

For IE8 compatibility, you need to use attachEvent:

if(obj.attachEvent) {
    elem.attachEvent('onblur', function(){
        alert("2");
    });
} else {
    obj.addEventListener('blur', function() {
        alert("2");
    }, false);
}

Of course it is recommended to create a function for this, instead of using inline as in the example above. An example of function is in the reply from Tuyoshi Vinicius.

Solution #2: Store the previous Handler

You can store the previous Handler in a variable, assign a new Handler, and call the old one from there:

var onBlurOriginal = obj.onblur;
obj.onblur = function() {
    alert("2");
    onBlurOriginal.call(this);
};

4

You can use the library jQuery that already has this type of cross-browser implementation if you do not use, the code below can be useful.

function listen(evnt, elem, func) {
    if (elem.addEventListener)  // W3C DOM
        elem.addEventListener(evnt,func,false);
    else if (elem.attachEvent) { // IE DOM
         var r = elem.attachEvent("on"+evnt, func);
    return r;
    }
    else window.alert('error');
}

listen("blur",document.getElementById('teste'),function(){
//sua função
})

0

This is an old javascript problem in browsers, easily reachable by the use of libraries, such as the jQuery.

Using jQuery your example would look like this:

<input id="txt" type="text" value="" />
<script>
function myFunction(obj) {
    $(obj).on("blur", function() {
        alert("2");
    });
}

$(function(){
    $("#txt")
    .on("focus", function () {
        myFunction(this);
    })
    .on("blur", function () {
        alert('1');
    });
});
</script>
  • 2

    Of course jQuery has many utilities, but include it only to solve this problem would be exaggeration.

  • Just see the problem of using jQuery if you are developing your own javascript library.

Browser other questions tagged

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