Working on a site that has multiple focus()
events spread throughout maybe a dozen js files that all handle giving focus to the first text input on the page (ie: on the login page the email field is given focus automatically). I'd like to disable this feature for all touch devices.
We're already using Modernizr, so I can just check for the .no-touch
class on the HTML tag to see if the user is on a touch device. However, in the interest of avoiding duplicate code and making this future proof (so we don't have to remember to check every time we add a new focus event) I'd like to just extend the native focus event to check for the .no-touch
class and only proceed when that class exists.
How would I extend the native focus()
event so that it checks the HTML tag for the .no-touch
class and continues when it is present, but ONLY runs this check when an anonymous function is not passed to the focus()
event?
For instance, there are occasions when we use focus with anonymous functions and I DON'T need to check for .no-touch
, like this:
$("#login-email-address").focus(function(){ ... });
Make sense? If not, let me know how I can clarify...
Something like this
(function($,M){
var nFocus = $.fn.focus;
$.fn.focus = function(f){
if(M.touch && !f)return this;
return nFocus.apply(this,arguments);
}
})(jQuery, Modernizer);