How to add an onBlur event without overwriting the original?

5


I have a code that is 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 is the link to my full role, so you can better understand my problem: link

    
asked by anonymous 14.03.2014 / 14:13

3 answers

4

Solution # 1 (Recommended): addEventListener

With addEventListener you can associate so many event handlers to an element as many as needed:

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

For compatibility with IE8, 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 function is in the Tuyoshi Vinicius answer .

Solution # 2: save the previous handler

You can save the previous handler to 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);
};
    
14.03.2014 / 14:22
4

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

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
})
    
14.03.2014 / 14:18
0

This is an old javascript problem in browsers, easily circumscribed by the use of libraries, such as 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>
    
14.03.2014 / 14:16