PDA

View Full Version : One element, multiple events



Rain Lover
06-19-2014, 02:50 AM
In jQuery you can easily do it like this:


$("#foo").focus(function () {
// Do this.
}).blur(function () {
// Do that.
});

Can we do something similar in JavaScript so we don't have to repeat #foo in two separate functions?

jscheuer1
06-19-2014, 03:47 AM
In regular javascript there is no #foo. The nearest (though not exact) equivalent would be document.getElementById('foo'). Something you could do along those lines would be:


var myfoo = document.getElementById('foo');
myfoo.onfocus = myfoo.onblur = function(e){
if(e.type === 'focus'){
//do this;
}else{
//do that;
}
};

But this is misleading because jQuery is assigning the events via addEventListener/attachEvent (whichever is first available), and is creating a reference to an object containing an (the first on the page if there are any) element with an id of foo regardless of whether or not that object has any members. And because one of the very reasons for using jQuery is to be able to use error reducing shortcuts of this nature unavailable in standard javascript. To do all that in standard javascript would be quite lengthy and involved.

Rain Lover
06-19-2014, 06:05 AM
In regular javascript there is no #foo. The nearest (though not exact) equivalent would be document.getElementById('foo'). Something you could do along those lines would be:


var myfoo = document.getElementById('foo');
myfoo.onfocus = myfoo.onblur = function(e){
if(e.type === 'focus'){
//do this;
}else{
//do that;
}
};

But this is misleading because jQuery is assigning the events via addEventListener/attachEvent (whichever is first available), and is creating a reference to an object containing an (the first on the page if there are any) element with an id of foo regardless of whether or not that object has any members. And because one of the very reasons for using jQuery is to be able to use error reducing shortcuts of this nature unavailable in standard javascript. To do all that in standard javascript would be quite lengthy and involved.

Thanks for the explanation! I finally decided to use two separate functions.