Related
I have a React app, I've added eventlisteners to the window. So, this way I can detect if the user actually viewing the page or not. On computer browser, everything works as expected.
But I tried this on IphoneX (it's irrelevant but the browser was Safari), and I came across this: If the user holds the bottom of the menu and swipe away all the open ones, then onBlur doesn't work. It stays on the onFocus event. So actually window.eventlistener not working properly on mobile.
Also, when I open the browser again (but not clicking anything, just opening the browser and view the page) onFocus event also not working. It waits for me to touch or click somewhere on the page.
How to handle user focus/blur completely on mobile side?
In the documentation for iOS / Safari supported events, they suggest pageshow and pagehide to listen for the kind of activity that I think you're talking about.
you can use window.navigator to get all OS and browser info
You can use requestAnimationFrame to check if the user is watching the page.
function isWatching(){
console.log("watching: " + Date.now());
requestAnimationFrame(isWatching);
}
requestAnimationFrame(isWatching);
See the example here: https://jsfiddle.net/t2r1sp56/ and you should also read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
You can use visibilityChange event and for the complete compatibility, you need to use webkit, ms, etc. prefix. I hope it helps :)
let visibilityEventName = '';
let hiddenProperty = '';
if (typeof document.hidden !== 'undefined') {
hiddenProperty = 'hidden';
visibilityEventName = 'visibilitychange';
} else if (typeof document.msHidden !== 'undefined') {
hiddenProperty = 'msHidden';
visibilityEventName = 'msvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
hiddenProperty = 'webkitHidden';
visibilityEventName = 'webkitvisibilitychange';
}
// check whether this API is available or not and then proceed
if (visibilityEventName) {
document.addEventListener(visibilityEventName, () => {
if (document[hiddenProperty]) {
// not visible
} else {
// visible
}
}, false);
}
I have solved the issue using below event listeners.
document.addEventListener("visibilitychange", handleActivity);
document.addEventListener("blur", handleActivityFalse);
window.addEventListener("blur", handleActivityFalse);
window.addEventListener("focus", handleActivityTrue);
document.addEventListener("focus", handleActivityTrue);
I've been experiencing an odd problem with IE10 when redirecting the page on an 'oninput' event (with no equivalent issue when using Chrome). I've produced the most pared-down version of the code that still exhibits the problem, as follows:
<html>
<head>
<script type="text/javascript">
function onChangeInputText()
{
window.location.href = "oninput_problem.html"; // Back to this page.
}
</script>
</head>
<body>
<input type="text"
oninput="onChangeInputText()"
value="£"
/>
</body>
</html>
On my Windows 7 PC using IE10, this code when browsed to (either by double clicking or via Apache) repeatedly redirects as if the act of initialising the value of the input text box itself is generating an immediate 'oninput' event. However, when I change the initial input text box value from the '£' symbol to a letter 'A', the repeated redirection doesn't occur.
I first noticed this problem as part of a project I'm working on. In that case, the user's input should cause a delayed page refresh, which began repeatedly redirecting when I entered a '£' symbol. As I say, the above code is the most pared-down version I produced in trying to track what was causing the issue.
Does anyone else experience this using IE10? If so, can anyone explain why IE10 is behaving this way?
I've found the following that appears to indicate that this may be a bug in IE10:
social.msdn.microsoft.com: Event oninput triggered on page load
Also, there's a follow-up bug report (within the page linked to above):
connect.microsoft.com: onInput event fires on loading the page when input #value is non-ASCII
EDITED TO ADD: At the bottom of the page pointed to by the second link, there's what would seem to be an unhelpful reply from Microsoft stating that they are unable to reproduce the bug described, so it may be a while before the issue is fixed...
There's anoter bug report which is still open :
http://connect.microsoft.com/IE/feedback/de...
For anyone who might encounter this, you can use this "class" as an alternative to the onInput event.
const getFieldWatcherInstance = (function(watchedElement, onElementValueChange){
let intervalReference = null;
let lastValue = null;
if(!watchedElement instanceof Element) return new Error('watchedElement is not an HTML Element');
if(typeof onElementValueChange !== 'function') return new Error('onElementValueChange is not a function');
return {
toggleFieldWatching : function(){
if(intervalReference){
clearInterval(intervalReference);
intervalReference = null;
}
else{
intervalReference = setInterval(function(){
const currentValue = watchedElement.value;
if(lastValue !== currentValue){
onElementValueChange(currentValue);
lastValue = currentValue;
}
}, 100);
}
}
};
});
Set it up like this:
const myInputChangeWatcher = getFieldWatcherInstance(<**insert real element reference here**>, function(newValue){
console.log('The new value is: ' + newValue);
});
call myInputChangeWatcher.toggleFieldWatching() in the onfocus and onblur events of the input
I've written a jQuery plug-in that's for use on both desktop and mobile devices. I wondered if there is a way with JavaScript to detect if the device has touch screen capability. I'm using jquery-mobile.js to detect the touch screen events and it works on iOS, Android etc., but I'd also like to write conditional statements based on whether the user's device has a touch screen.
Is that possible?
UPDATE 2021
To see the old answers: check the history. I decided to start on a clean slate as it was getting out of hands when keeping the history in the post.
My original answer said that it could be a good idea to use the same function as Modernizr was using, but that is not valid anymore as they removed the "touchevents" tests on this PR: https://github.com/Modernizr/Modernizr/pull/2432 due to it being a confusing subject.
With that said this should be a fairly ok way of detecting if the browser has "touch capabilities":
function isTouchDevice() {
return (('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
}
But for more advanced use cases far more smarter persons than me have written about this subject, I would recommend reading those articles:
Stu Cox: You Can't Detect a Touchscreen
Detecting touch: it's the 'why', not the 'how'
Getting touchy presentation by Patrick H. Lauke
Update: Please read blmstr's answer below before pulling a whole feature detection library into your project. Detecting actual touch support is more complex, and Modernizr only covers a basic use case.
Modernizr is a great, lightweight way to do all kinds of feature detection on any site.
It simply adds classes to the html element for each feature.
You can then target those features easily in CSS and JS. For example:
html.touch div {
width: 480px;
}
html.no-touch div {
width: auto;
}
And Javascript (jQuery example):
$('html.touch #popup').hide();
As Modernizr doesn't detect IE10 on Windows Phone 8/WinRT, a simple, cross-browser solution is:
var supportsTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints;
You only ever need to check once as the device won't suddenly support or not support touch, so just store it in a variable so you can use it multiple times more efficiently.
Since the introduction of interaction media features you simply can do:
if(window.matchMedia("(pointer: coarse)").matches) {
// touchscreen
}
https://www.w3.org/TR/mediaqueries-4/#descdef-media-any-pointer
Update (due to comments): The above solution is to detect if a "coarse pointer" - usually a touch screen - is the primary input device. In case you want to dectect if a device with e.g. a mouse also has a touch screen you may use any-pointer: coarse instead.
For more information have a look here: Detecting that the browser has no mouse and is touch-only
Using all the comments above I've assembled the following code that is working for my needs:
var isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0));
I have tested this on iPad, Android (Browser and Chrome), Blackberry Playbook, iPhone 4s, Windows Phone 8, IE 10, IE 8, IE 10 (Windows 8 with Touchscreen), Opera, Chrome and Firefox.
It currently fails on Windows Phone 7 and I haven't been able to find a solution for that browser yet.
Hope someone finds this useful.
I like this one:
function isTouchDevice(){
return window.ontouchstart !== undefined;
}
alert(isTouchDevice());
If you use Modernizr, it is very easy to use Modernizr.touch as mentioned earlier.
However, I prefer using a combination of Modernizr.touch and user agent testing, just to be safe.
var deviceAgent = navigator.userAgent.toLowerCase();
var isTouchDevice = Modernizr.touch ||
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/) ||
deviceAgent.match(/(iemobile)/) ||
deviceAgent.match(/iphone/i) ||
deviceAgent.match(/ipad/i) ||
deviceAgent.match(/ipod/i) ||
deviceAgent.match(/blackberry/i) ||
deviceAgent.match(/bada/i));
if (isTouchDevice) {
//Do something touchy
} else {
//Can't touch this
}
If you don't use Modernizr, you can simply replace the Modernizr.touch function above with ('ontouchstart' in document.documentElement)
Also note that testing the user agent iemobile will give you broader range of detected Microsoft mobile devices than Windows Phone.
Also see this SO question
We tried the modernizr implementation, but detecting the touch events is not consistent anymore (IE 10 has touch events on windows desktop, IE 11 works, because the've dropped touch events and added pointer api).
So we decided to optimize the website as a touch site as long as we don't know what input type the user has. This is more reliable than any other solution.
Our researches say, that most desktop users move with their mouse over the screen before they click, so we can detect them and change the behaviour before they are able to click or hover anything.
This is a simplified version of our code:
var isTouch = true;
window.addEventListener('mousemove', function mouseMoveDetector() {
isTouch = false;
window.removeEventListener('mousemove', mouseMoveDetector);
});
There is something better than checking if they have a touchScreen, is to check if they are using it, plus that's easier to check.
if (window.addEventListener) {
var once = false;
window.addEventListener('touchstart', function(){
if (!once) {
once = true;
// Do what you need for touch-screens only
}
});
}
Working Fiddle
I have achieved it like this;
function isTouchDevice(){
return true == ("ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch);
}
if(isTouchDevice()===true) {
alert('Touch Device'); //your logic for touch device
}
else {
alert('Not a Touch Device'); //your logic for non touch device
}
This one works well even in Windows Surface tablets !!!
function detectTouchSupport {
msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture,
touchSupport = (( "ontouchstart" in window ) || msGesture || window.DocumentTouch && document instanceof DocumentTouch);
if(touchSupport) {
$("html").addClass("ci_touch");
}
else {
$("html").addClass("ci_no_touch");
}
}
The biggest "gotcha" with trying to detect touch is on hybrid devices that support both touch and the trackpad/mouse. Even if you're able to correctly detect whether the user's device supports touch, what you really need to do is detect what input device the user is currently using. There's a detailed write up of this challenge and a possible solution here.
Basically the approach to figuring out whether a user just touched the screen or used a mouse/ trackpad instead is to register both a touchstart and mouseover event on the page:
document.addEventListener('touchstart', functionref, false) // on user tap, "touchstart" fires first
document.addEventListener('mouseover', functionref, false) // followed by mouse event, ie: "mouseover"
A touch action will trigger both of these events, though the former (touchstart) always first on most devices. So counting on this predictable sequence of events, you can create a mechanism that dynamically adds or removes a can-touch class to the document root to reflect the current input type of the user at this moment on the document:
;(function(){
var isTouch = false //var to indicate current input type (is touch versus no touch)
var isTouchTimer
var curRootClass = '' //var indicating current document root class ("can-touch" or "")
function addtouchclass(e){
clearTimeout(isTouchTimer)
isTouch = true
if (curRootClass != 'can-touch'){ //add "can-touch' class if it's not already present
curRootClass = 'can-touch'
document.documentElement.classList.add(curRootClass)
}
isTouchTimer = setTimeout(function(){isTouch = false}, 500) //maintain "istouch" state for 500ms so removetouchclass doesn't get fired immediately following a touch event
}
function removetouchclass(e){
if (!isTouch && curRootClass == 'can-touch'){ //remove 'can-touch' class if not triggered by a touch event and class is present
isTouch = false
curRootClass = ''
document.documentElement.classList.remove('can-touch')
}
}
document.addEventListener('touchstart', addtouchclass, false) //this event only gets called when input type is touch
document.addEventListener('mouseover', removetouchclass, false) //this event gets called when input type is everything from touch to mouse/ trackpad
})();
More details here.
I used pieces of the code above to detect whether touch, so my fancybox iframes would show up on desktop computers and not on touch. I noticed that Opera Mini for Android 4.0 was still registering as a non-touch device when using blmstr's code alone. (Does anyone know why?)
I ended up using:
<script>
$(document).ready(function() {
var ua = navigator.userAgent;
function is_touch_device() {
try {
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
}
}
if ((is_touch_device()) || ua.match(/(iPhone|iPod|iPad)/)
|| ua.match(/BlackBerry/) || ua.match(/Android/)) {
// Touch browser
} else {
// Lightbox code
}
});
</script>
Actually, I researched this question and consider all situations. because it is a big issue on my project too. So I reach the below function, it works for all versions of all browsers on all devices:
const isTouchDevice = () => {
const prefixes = ['', '-webkit-', '-moz-', '-o-', '-ms-', ''];
const mq = query => window.matchMedia(query).matches;
if (
'ontouchstart' in window ||
(window.DocumentTouch && document instanceof DocumentTouch)
) {
return true;
}
return mq(['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join(''));
};
Hint: Definitely, the isTouchDevice just returns boolean values.
Check out this post, it gives a really nice code snippet for what to do when touch devices are detected or what to do if touchstart event is called:
$(function(){
if(window.Touch) {
touch_detect.auto_detected();
} else {
document.ontouchstart = touch_detect.surface;
}
}); // End loaded jQuery
var touch_detect = {
auto_detected: function(event){
/* add everything you want to do onLoad here (eg. activating hover controls) */
alert('this was auto detected');
activateTouchArea();
},
surface: function(event){
/* add everything you want to do ontouchstart here (eg. drag & drop) - you can fire this in both places */
alert('this was detected by touching');
activateTouchArea();
}
}; // touch_detect
function activateTouchArea(){
/* make sure our screen doesn't scroll when we move the "touchable area" */
var element = document.getElementById('element_id');
element.addEventListener("touchstart", touchStart, false);
}
function touchStart(event) {
/* modularize preventing the default behavior so we can use it again */
event.preventDefault();
}
I would avoid using screen width to determine if a device is a touch device. There are touch screens much larger than 699px, think of Windows 8. Navigatior.userAgent may be nice to override false postives.
I would recommend checking out this issue on Modernizr.
Are you wanting to test if the device supports touch events or is a touch device. Unfortunately, that's not the same thing.
No, it's not possible. The excellent answers given are only ever partial, because any given method will produce false positives and false negatives. Even the browser doesn't always know if a touchscreen is present, due to OS APIs, and the fact can change during a browser session, particularly with KVM-type arrangements.
See further details in this excellent article:
http://www.stucox.com/blog/you-cant-detect-a-touchscreen/
The article suggests you reconsider the assumptions that make you want to detect touchscreens, they're probably wrong. (I checked my own for my app, and my assumptions were indeed wrong!)
The article concludes:
For layouts, assume everyone has a touchscreen. Mouse users can use
large UI controls much more easily than touch users can use small
ones. The same goes for hover states.
For events and interactions, assume anyone may have a touchscreen.
Implement keyboard, mouse and touch interactions alongside each other,
ensuring none block each other.
Many of these work but either require jQuery, or javascript linters complain about the syntax. Considering your initial question asks for a "JavaScript" (not jQuery, not Modernizr) way of solving this, here's a simple function that works every time. It's also about as minimal as you can get.
function isTouchDevice() {
return !!window.ontouchstart;
}
console.log(isTouchDevice());
One last benefit I'll mention is that this code is framework and device agnostic. Enjoy!
I think the best method is:
var isTouchDevice =
(('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
if(!isTouchDevice){
/* Code for touch device /*
}else{
/* Code for non touch device */
}
It looks like Chrome 24 now support touch events, probably for Windows 8. So the code posted here no longer works. Instead of trying to detect if touch is supported by the browser, I'm now binding both touch and click events and making sure only one is called:
myCustomBind = function(controlName, callback) {
$(controlName).bind('touchend click', function(e) {
e.stopPropagation();
e.preventDefault();
callback.call();
});
};
And then calling it:
myCustomBind('#mnuRealtime', function () { ... });
Hope this helps !
All browser supported except Firefox for desktop always TRUE because of Firefox for desktop support responsive design for developer even you click Touch-Button or not!
I hope Mozilla will fix this in next version.
I'm using Firefox 28 desktop.
function isTouch()
{
return !!("ontouchstart" in window) || !!(navigator.msMaxTouchPoints);
}
jQuery v1.11.3
There is a lot of good information in the answers provided. But, recently I spent a lot of time trying to actually tie everything together into a working solution for the accomplishing two things:
Detect that the device in use is a touch screen type device.
Detect that the device was tapped.
Besides this post and Detecting touch screen devices with Javascript, I found this post by Patrick Lauke extremely helpful: https://hacks.mozilla.org/2013/04/detecting-touch-its-the-why-not-the-how/
Here is the code...
$(document).ready(function() {
//The page is "ready" and the document can be manipulated.
if (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0))
{
//If the device is a touch capable device, then...
$(document).on("touchstart", "a", function() {
//Do something on tap.
});
}
else
{
null;
}
});
Important! The *.on( events [, selector ] [, data ], handler ) method needs to have a selector, usually an element, that can handle the "touchstart" event, or any other like event associated with touches. In this case, it is the hyperlink element "a".
Now, you don't need to handle the regular mouse clicking in JavaScript, because you can use CSS to handle these events using selectors for the hyperlink "a" element like so:
/* unvisited link */
a:link
{
}
/* visited link */
a:visited
{
}
/* mouse over link */
a:hover
{
}
/* selected link */
a:active
{
}
Note: There are other selectors as well...
The problem
Due to hybrid devices which use a combination of touch and mouse input, you need to be able dynamically change the state / variable which controls whether a piece of code should run if the user is a touch user or not.
Touch devices also fire mousemove on tap.
Solution
Assume touch is false on load.
Wait until a touchstart event is fired, then set it to true.
If touchstart was fired, add a mousemove handler.
If the time between two mousemove events firing was less than 20ms, assume they are using a mouse as input. Remove the event as it's no longer needed and mousemove is an expensive event for mouse devices.
As soon as touchstart is fired again (user went back to using touch), the variable is set back to true. And repeat the process so it's determined in a dynamic fashion. If by some miracle mousemove gets fired twice on touch absurdly quickly (in my testing it's virtually impossible to do it within 20ms), the next touchstart will set it back to true.
Tested on Safari iOS and Chrome for Android.
Note: not 100% sure on the pointer-events for MS Surface, etc.
Codepen demo
const supportsTouch = 'ontouchstart' in window;
let isUsingTouch = false;
// `touchstart`, `pointerdown`
const touchHandler = () => {
isUsingTouch = true;
document.addEventListener('mousemove', mousemoveHandler);
};
// use a simple closure to store previous time as internal state
const mousemoveHandler = (() => {
let time;
return () => {
const now = performance.now();
if (now - time < 20) {
isUsingTouch = false;
document.removeEventListener('mousemove', mousemoveHandler);
}
time = now;
}
})();
// add listeners
if (supportsTouch) {
document.addEventListener('touchstart', touchHandler);
} else if (navigator.maxTouchPoints || navigator.msMaxTouchPoints) {
document.addEventListener('pointerdown', touchHandler);
}
Right so there is a huge debate over detecting touch/non-touch devices. The number of window tablets and the size of tablets is increasing creating another set of headaches for us web developers.
I have used and tested blmstr's answer for a menu. The menu works like this: when the page loads the script detects if this is a touch or non touch device. Based on that the menu would work on hover (non-touch) or on click/tap (touch).
In most of the cases blmstr's scripts seemed to work just fine (specifically the 2018 one). BUT there was still that one device that would be detected as touch when it is not or vice versa.
For this reason I did a bit of digging and thanks to this article I replaced a few lines from blmstr's 4th script into this:
function is_touch_device4() {
if ("ontouchstart" in window)
return true;
if (window.DocumentTouch && document instanceof DocumentTouch)
return true;
return window.matchMedia( "(pointer: coarse)" ).matches;
}
alert('Is touch device: '+is_touch_device4());
console.log('Is touch device: '+is_touch_device4());
Because of the lockdown have a limited supply of touch devices to test this one but so far the above works great.
I would appreceate if anyone with a desktop touch device (ex. surface tablet) can confirm if script works all right.
Now in terms of support the pointer: coarse media query seems to be supported. I kept the lines above since I had (for some reason) issues on mobile firefox but the lines above the media query do the trick.
Thanks
var isTouchScreen = 'createTouch' in document;
or
var isTouchScreen = 'createTouch' in document || screen.width <= 699 ||
ua.match(/(iPhone|iPod|iPad)/) || ua.match(/BlackBerry/) ||
ua.match(/Android/);
would be a more thorough check I suppose.
I use:
if(jQuery.support.touch){
alert('Touch enabled');
}
in jQuery mobile 1.0.1
You can install modernizer and use a simple touch event. This is very effective and works on every device I have tested it on including windows surface!
I've created a jsFiddle
function isTouchDevice(){
if(Modernizr.hasEvent('touchstart') || navigator.userAgent.search(/Touch/i) != -1){
alert("is touch");
return true;
}else{
alert("is not touch");
return false;
}
}
I also struggled a lot with different options on how to detect in Javascript whether the page is displayed on a touch screen device or not.
IMO, as of now, no real option exists to detect the option properly.
Browsers either report touch events on desktop machines (because the OS maybe touch-ready), or some solutions don't work on all mobile devices.
In the end, I realized that I was following the wrong approach from the start:
If my page was to look similar on touch and non-touch devices, I maybe shouldn't have to worry about detecting the property at all:
My scenario was to deactivate tooltips over buttons on touch devices as they lead to double-taps where I wanted a single tap to activate the button.
My solution was to refactor the view so that no tooltip was needed over a button, and in the end I didn't need to detect the touch device from Javascript with methods that all have their drawbacks.
The practical answer seems to be one that considers the context:
1) Public site (no login)
Code the UI to work with both options together.
2) Login site
Capture whether a mouse-move occurred on the login form, and save this into a hidden input. The value is passed with the login credentials and added to the user's session, so it can be used for the duration of the session.
Jquery to add to login page only:
$('#istouch').val(1); // <-- value will be submitted with login form
if (window.addEventListener) {
window.addEventListener('mousemove', function mouseMoveListener(){
// Update hidden input value to false, and stop listening
$('#istouch').val(0);
window.removeEventListener('mousemove', mouseMoveListener);
});
}
(+1 to #Dave Burt and +1 to #Martin Lantzsch on their answers)
Extent jQuery support object:
jQuery.support.touch = 'ontouchend' in document;
And now you can check it anywhere, like this:
if( jQuery.support.touch )
// do touch stuff
I've written a jQuery plug-in that's for use on both desktop and mobile devices. I wondered if there is a way with JavaScript to detect if the device has touch screen capability. I'm using jquery-mobile.js to detect the touch screen events and it works on iOS, Android etc., but I'd also like to write conditional statements based on whether the user's device has a touch screen.
Is that possible?
UPDATE 2021
To see the old answers: check the history. I decided to start on a clean slate as it was getting out of hands when keeping the history in the post.
My original answer said that it could be a good idea to use the same function as Modernizr was using, but that is not valid anymore as they removed the "touchevents" tests on this PR: https://github.com/Modernizr/Modernizr/pull/2432 due to it being a confusing subject.
With that said this should be a fairly ok way of detecting if the browser has "touch capabilities":
function isTouchDevice() {
return (('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
}
But for more advanced use cases far more smarter persons than me have written about this subject, I would recommend reading those articles:
Stu Cox: You Can't Detect a Touchscreen
Detecting touch: it's the 'why', not the 'how'
Getting touchy presentation by Patrick H. Lauke
Update: Please read blmstr's answer below before pulling a whole feature detection library into your project. Detecting actual touch support is more complex, and Modernizr only covers a basic use case.
Modernizr is a great, lightweight way to do all kinds of feature detection on any site.
It simply adds classes to the html element for each feature.
You can then target those features easily in CSS and JS. For example:
html.touch div {
width: 480px;
}
html.no-touch div {
width: auto;
}
And Javascript (jQuery example):
$('html.touch #popup').hide();
As Modernizr doesn't detect IE10 on Windows Phone 8/WinRT, a simple, cross-browser solution is:
var supportsTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints;
You only ever need to check once as the device won't suddenly support or not support touch, so just store it in a variable so you can use it multiple times more efficiently.
Since the introduction of interaction media features you simply can do:
if(window.matchMedia("(pointer: coarse)").matches) {
// touchscreen
}
https://www.w3.org/TR/mediaqueries-4/#descdef-media-any-pointer
Update (due to comments): The above solution is to detect if a "coarse pointer" - usually a touch screen - is the primary input device. In case you want to dectect if a device with e.g. a mouse also has a touch screen you may use any-pointer: coarse instead.
For more information have a look here: Detecting that the browser has no mouse and is touch-only
Using all the comments above I've assembled the following code that is working for my needs:
var isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0));
I have tested this on iPad, Android (Browser and Chrome), Blackberry Playbook, iPhone 4s, Windows Phone 8, IE 10, IE 8, IE 10 (Windows 8 with Touchscreen), Opera, Chrome and Firefox.
It currently fails on Windows Phone 7 and I haven't been able to find a solution for that browser yet.
Hope someone finds this useful.
I like this one:
function isTouchDevice(){
return window.ontouchstart !== undefined;
}
alert(isTouchDevice());
If you use Modernizr, it is very easy to use Modernizr.touch as mentioned earlier.
However, I prefer using a combination of Modernizr.touch and user agent testing, just to be safe.
var deviceAgent = navigator.userAgent.toLowerCase();
var isTouchDevice = Modernizr.touch ||
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/) ||
deviceAgent.match(/(iemobile)/) ||
deviceAgent.match(/iphone/i) ||
deviceAgent.match(/ipad/i) ||
deviceAgent.match(/ipod/i) ||
deviceAgent.match(/blackberry/i) ||
deviceAgent.match(/bada/i));
if (isTouchDevice) {
//Do something touchy
} else {
//Can't touch this
}
If you don't use Modernizr, you can simply replace the Modernizr.touch function above with ('ontouchstart' in document.documentElement)
Also note that testing the user agent iemobile will give you broader range of detected Microsoft mobile devices than Windows Phone.
Also see this SO question
We tried the modernizr implementation, but detecting the touch events is not consistent anymore (IE 10 has touch events on windows desktop, IE 11 works, because the've dropped touch events and added pointer api).
So we decided to optimize the website as a touch site as long as we don't know what input type the user has. This is more reliable than any other solution.
Our researches say, that most desktop users move with their mouse over the screen before they click, so we can detect them and change the behaviour before they are able to click or hover anything.
This is a simplified version of our code:
var isTouch = true;
window.addEventListener('mousemove', function mouseMoveDetector() {
isTouch = false;
window.removeEventListener('mousemove', mouseMoveDetector);
});
There is something better than checking if they have a touchScreen, is to check if they are using it, plus that's easier to check.
if (window.addEventListener) {
var once = false;
window.addEventListener('touchstart', function(){
if (!once) {
once = true;
// Do what you need for touch-screens only
}
});
}
Working Fiddle
I have achieved it like this;
function isTouchDevice(){
return true == ("ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch);
}
if(isTouchDevice()===true) {
alert('Touch Device'); //your logic for touch device
}
else {
alert('Not a Touch Device'); //your logic for non touch device
}
This one works well even in Windows Surface tablets !!!
function detectTouchSupport {
msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture,
touchSupport = (( "ontouchstart" in window ) || msGesture || window.DocumentTouch && document instanceof DocumentTouch);
if(touchSupport) {
$("html").addClass("ci_touch");
}
else {
$("html").addClass("ci_no_touch");
}
}
The biggest "gotcha" with trying to detect touch is on hybrid devices that support both touch and the trackpad/mouse. Even if you're able to correctly detect whether the user's device supports touch, what you really need to do is detect what input device the user is currently using. There's a detailed write up of this challenge and a possible solution here.
Basically the approach to figuring out whether a user just touched the screen or used a mouse/ trackpad instead is to register both a touchstart and mouseover event on the page:
document.addEventListener('touchstart', functionref, false) // on user tap, "touchstart" fires first
document.addEventListener('mouseover', functionref, false) // followed by mouse event, ie: "mouseover"
A touch action will trigger both of these events, though the former (touchstart) always first on most devices. So counting on this predictable sequence of events, you can create a mechanism that dynamically adds or removes a can-touch class to the document root to reflect the current input type of the user at this moment on the document:
;(function(){
var isTouch = false //var to indicate current input type (is touch versus no touch)
var isTouchTimer
var curRootClass = '' //var indicating current document root class ("can-touch" or "")
function addtouchclass(e){
clearTimeout(isTouchTimer)
isTouch = true
if (curRootClass != 'can-touch'){ //add "can-touch' class if it's not already present
curRootClass = 'can-touch'
document.documentElement.classList.add(curRootClass)
}
isTouchTimer = setTimeout(function(){isTouch = false}, 500) //maintain "istouch" state for 500ms so removetouchclass doesn't get fired immediately following a touch event
}
function removetouchclass(e){
if (!isTouch && curRootClass == 'can-touch'){ //remove 'can-touch' class if not triggered by a touch event and class is present
isTouch = false
curRootClass = ''
document.documentElement.classList.remove('can-touch')
}
}
document.addEventListener('touchstart', addtouchclass, false) //this event only gets called when input type is touch
document.addEventListener('mouseover', removetouchclass, false) //this event gets called when input type is everything from touch to mouse/ trackpad
})();
More details here.
I used pieces of the code above to detect whether touch, so my fancybox iframes would show up on desktop computers and not on touch. I noticed that Opera Mini for Android 4.0 was still registering as a non-touch device when using blmstr's code alone. (Does anyone know why?)
I ended up using:
<script>
$(document).ready(function() {
var ua = navigator.userAgent;
function is_touch_device() {
try {
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
}
}
if ((is_touch_device()) || ua.match(/(iPhone|iPod|iPad)/)
|| ua.match(/BlackBerry/) || ua.match(/Android/)) {
// Touch browser
} else {
// Lightbox code
}
});
</script>
Actually, I researched this question and consider all situations. because it is a big issue on my project too. So I reach the below function, it works for all versions of all browsers on all devices:
const isTouchDevice = () => {
const prefixes = ['', '-webkit-', '-moz-', '-o-', '-ms-', ''];
const mq = query => window.matchMedia(query).matches;
if (
'ontouchstart' in window ||
(window.DocumentTouch && document instanceof DocumentTouch)
) {
return true;
}
return mq(['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join(''));
};
Hint: Definitely, the isTouchDevice just returns boolean values.
Check out this post, it gives a really nice code snippet for what to do when touch devices are detected or what to do if touchstart event is called:
$(function(){
if(window.Touch) {
touch_detect.auto_detected();
} else {
document.ontouchstart = touch_detect.surface;
}
}); // End loaded jQuery
var touch_detect = {
auto_detected: function(event){
/* add everything you want to do onLoad here (eg. activating hover controls) */
alert('this was auto detected');
activateTouchArea();
},
surface: function(event){
/* add everything you want to do ontouchstart here (eg. drag & drop) - you can fire this in both places */
alert('this was detected by touching');
activateTouchArea();
}
}; // touch_detect
function activateTouchArea(){
/* make sure our screen doesn't scroll when we move the "touchable area" */
var element = document.getElementById('element_id');
element.addEventListener("touchstart", touchStart, false);
}
function touchStart(event) {
/* modularize preventing the default behavior so we can use it again */
event.preventDefault();
}
I would avoid using screen width to determine if a device is a touch device. There are touch screens much larger than 699px, think of Windows 8. Navigatior.userAgent may be nice to override false postives.
I would recommend checking out this issue on Modernizr.
Are you wanting to test if the device supports touch events or is a touch device. Unfortunately, that's not the same thing.
No, it's not possible. The excellent answers given are only ever partial, because any given method will produce false positives and false negatives. Even the browser doesn't always know if a touchscreen is present, due to OS APIs, and the fact can change during a browser session, particularly with KVM-type arrangements.
See further details in this excellent article:
http://www.stucox.com/blog/you-cant-detect-a-touchscreen/
The article suggests you reconsider the assumptions that make you want to detect touchscreens, they're probably wrong. (I checked my own for my app, and my assumptions were indeed wrong!)
The article concludes:
For layouts, assume everyone has a touchscreen. Mouse users can use
large UI controls much more easily than touch users can use small
ones. The same goes for hover states.
For events and interactions, assume anyone may have a touchscreen.
Implement keyboard, mouse and touch interactions alongside each other,
ensuring none block each other.
Many of these work but either require jQuery, or javascript linters complain about the syntax. Considering your initial question asks for a "JavaScript" (not jQuery, not Modernizr) way of solving this, here's a simple function that works every time. It's also about as minimal as you can get.
function isTouchDevice() {
return !!window.ontouchstart;
}
console.log(isTouchDevice());
One last benefit I'll mention is that this code is framework and device agnostic. Enjoy!
I think the best method is:
var isTouchDevice =
(('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
if(!isTouchDevice){
/* Code for touch device /*
}else{
/* Code for non touch device */
}
It looks like Chrome 24 now support touch events, probably for Windows 8. So the code posted here no longer works. Instead of trying to detect if touch is supported by the browser, I'm now binding both touch and click events and making sure only one is called:
myCustomBind = function(controlName, callback) {
$(controlName).bind('touchend click', function(e) {
e.stopPropagation();
e.preventDefault();
callback.call();
});
};
And then calling it:
myCustomBind('#mnuRealtime', function () { ... });
Hope this helps !
All browser supported except Firefox for desktop always TRUE because of Firefox for desktop support responsive design for developer even you click Touch-Button or not!
I hope Mozilla will fix this in next version.
I'm using Firefox 28 desktop.
function isTouch()
{
return !!("ontouchstart" in window) || !!(navigator.msMaxTouchPoints);
}
jQuery v1.11.3
There is a lot of good information in the answers provided. But, recently I spent a lot of time trying to actually tie everything together into a working solution for the accomplishing two things:
Detect that the device in use is a touch screen type device.
Detect that the device was tapped.
Besides this post and Detecting touch screen devices with Javascript, I found this post by Patrick Lauke extremely helpful: https://hacks.mozilla.org/2013/04/detecting-touch-its-the-why-not-the-how/
Here is the code...
$(document).ready(function() {
//The page is "ready" and the document can be manipulated.
if (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0))
{
//If the device is a touch capable device, then...
$(document).on("touchstart", "a", function() {
//Do something on tap.
});
}
else
{
null;
}
});
Important! The *.on( events [, selector ] [, data ], handler ) method needs to have a selector, usually an element, that can handle the "touchstart" event, or any other like event associated with touches. In this case, it is the hyperlink element "a".
Now, you don't need to handle the regular mouse clicking in JavaScript, because you can use CSS to handle these events using selectors for the hyperlink "a" element like so:
/* unvisited link */
a:link
{
}
/* visited link */
a:visited
{
}
/* mouse over link */
a:hover
{
}
/* selected link */
a:active
{
}
Note: There are other selectors as well...
The problem
Due to hybrid devices which use a combination of touch and mouse input, you need to be able dynamically change the state / variable which controls whether a piece of code should run if the user is a touch user or not.
Touch devices also fire mousemove on tap.
Solution
Assume touch is false on load.
Wait until a touchstart event is fired, then set it to true.
If touchstart was fired, add a mousemove handler.
If the time between two mousemove events firing was less than 20ms, assume they are using a mouse as input. Remove the event as it's no longer needed and mousemove is an expensive event for mouse devices.
As soon as touchstart is fired again (user went back to using touch), the variable is set back to true. And repeat the process so it's determined in a dynamic fashion. If by some miracle mousemove gets fired twice on touch absurdly quickly (in my testing it's virtually impossible to do it within 20ms), the next touchstart will set it back to true.
Tested on Safari iOS and Chrome for Android.
Note: not 100% sure on the pointer-events for MS Surface, etc.
Codepen demo
const supportsTouch = 'ontouchstart' in window;
let isUsingTouch = false;
// `touchstart`, `pointerdown`
const touchHandler = () => {
isUsingTouch = true;
document.addEventListener('mousemove', mousemoveHandler);
};
// use a simple closure to store previous time as internal state
const mousemoveHandler = (() => {
let time;
return () => {
const now = performance.now();
if (now - time < 20) {
isUsingTouch = false;
document.removeEventListener('mousemove', mousemoveHandler);
}
time = now;
}
})();
// add listeners
if (supportsTouch) {
document.addEventListener('touchstart', touchHandler);
} else if (navigator.maxTouchPoints || navigator.msMaxTouchPoints) {
document.addEventListener('pointerdown', touchHandler);
}
Right so there is a huge debate over detecting touch/non-touch devices. The number of window tablets and the size of tablets is increasing creating another set of headaches for us web developers.
I have used and tested blmstr's answer for a menu. The menu works like this: when the page loads the script detects if this is a touch or non touch device. Based on that the menu would work on hover (non-touch) or on click/tap (touch).
In most of the cases blmstr's scripts seemed to work just fine (specifically the 2018 one). BUT there was still that one device that would be detected as touch when it is not or vice versa.
For this reason I did a bit of digging and thanks to this article I replaced a few lines from blmstr's 4th script into this:
function is_touch_device4() {
if ("ontouchstart" in window)
return true;
if (window.DocumentTouch && document instanceof DocumentTouch)
return true;
return window.matchMedia( "(pointer: coarse)" ).matches;
}
alert('Is touch device: '+is_touch_device4());
console.log('Is touch device: '+is_touch_device4());
Because of the lockdown have a limited supply of touch devices to test this one but so far the above works great.
I would appreceate if anyone with a desktop touch device (ex. surface tablet) can confirm if script works all right.
Now in terms of support the pointer: coarse media query seems to be supported. I kept the lines above since I had (for some reason) issues on mobile firefox but the lines above the media query do the trick.
Thanks
var isTouchScreen = 'createTouch' in document;
or
var isTouchScreen = 'createTouch' in document || screen.width <= 699 ||
ua.match(/(iPhone|iPod|iPad)/) || ua.match(/BlackBerry/) ||
ua.match(/Android/);
would be a more thorough check I suppose.
I use:
if(jQuery.support.touch){
alert('Touch enabled');
}
in jQuery mobile 1.0.1
You can install modernizer and use a simple touch event. This is very effective and works on every device I have tested it on including windows surface!
I've created a jsFiddle
function isTouchDevice(){
if(Modernizr.hasEvent('touchstart') || navigator.userAgent.search(/Touch/i) != -1){
alert("is touch");
return true;
}else{
alert("is not touch");
return false;
}
}
I also struggled a lot with different options on how to detect in Javascript whether the page is displayed on a touch screen device or not.
IMO, as of now, no real option exists to detect the option properly.
Browsers either report touch events on desktop machines (because the OS maybe touch-ready), or some solutions don't work on all mobile devices.
In the end, I realized that I was following the wrong approach from the start:
If my page was to look similar on touch and non-touch devices, I maybe shouldn't have to worry about detecting the property at all:
My scenario was to deactivate tooltips over buttons on touch devices as they lead to double-taps where I wanted a single tap to activate the button.
My solution was to refactor the view so that no tooltip was needed over a button, and in the end I didn't need to detect the touch device from Javascript with methods that all have their drawbacks.
The practical answer seems to be one that considers the context:
1) Public site (no login)
Code the UI to work with both options together.
2) Login site
Capture whether a mouse-move occurred on the login form, and save this into a hidden input. The value is passed with the login credentials and added to the user's session, so it can be used for the duration of the session.
Jquery to add to login page only:
$('#istouch').val(1); // <-- value will be submitted with login form
if (window.addEventListener) {
window.addEventListener('mousemove', function mouseMoveListener(){
// Update hidden input value to false, and stop listening
$('#istouch').val(0);
window.removeEventListener('mousemove', mouseMoveListener);
});
}
(+1 to #Dave Burt and +1 to #Martin Lantzsch on their answers)
Extent jQuery support object:
jQuery.support.touch = 'ontouchend' in document;
And now you can check it anywhere, like this:
if( jQuery.support.touch )
// do touch stuff
Is it possible to clear an <input type='file' /> control value with jQuery? I've tried the following:
$('#control').attr({ value: '' });
But it's not working.
Easy: you wrap a <form> around the element, call reset on the form, then remove the form using .unwrap(). Unlike the .clone() solutions otherwise in this thread, you end up with the same element at the end (including custom properties that were set on it).
Tested and working in Opera, Firefox, Safari, Chrome and IE6+. Also works on other types of form elements, with the exception of type="hidden".
window.reset = function(e) {
e.wrap('<form>').closest('form').get(0).reset();
e.unwrap();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input id="file" type="file">
<br>
<input id="text" type="text" value="Original">
</form>
<button onclick="reset($('#file'))">Reset file</button>
<button onclick="reset($('#text'))">Reset text</button>
JSFiddle
As Timo notes below, if you have the buttons to trigger the reset of the field inside of the <form>, you must call .preventDefault() on the event to prevent the <button> from triggering a submit.
EDIT
Does not work in IE 11 due to an unfixed bug. The text (file name) is cleared on the input, but its File list remains populated.
Quick answer: replace it.
In the code below I use the replaceWith jQuery method to replace the control with a clone of itself. In the event you have any handlers bound to events on this control, we'll want to preserve those as well. To do this we pass in true as the first parameter of the clone method.
<input type="file" id="control"/>
<button id="clear">Clear</button>
var control = $("#control");
$("#clear").on("click", function () {
control.replaceWith( control = control.clone( true ) );
});
Fiddle: http://jsfiddle.net/jonathansampson/dAQVM/
If cloning, while preserving event handlers, presents any issues you could consider using event delegation to handle clicks on this control from a parent element:
$("form").on("focus", "#control", doStuff);
This prevents the need for any handlers to be cloned along with the element when the control is being refreshed.
Jquery is supposed to take care of the cross-browser/older browser issues for you.
This works on modern browsers that I tested: Chromium v25, Firefox v20, Opera v12.14
Using jquery 1.9.1
HTML
<input id="fileopen" type="file" value="" />
<button id="clear">Clear</button>
Jquery
$("#clear").click(function () {
$("#fileopen").val("");
});
On jsfiddle
The following javascript solution also worked for me on the browsers mention above.
document.getElementById("clear").addEventListener("click", function () {
document.getElementById("fileopen").value = "";
}, false);
On jsfiddle
I have no way to test with IE, but theoretically this should work. If IE is different enough that the Javascript version does not work because MS have done it in a different way, the jquery method should in my opinion deal with it for you, else it would be worth pointing it out to the jquery team along with the method that IE requires. (I see people saying "this won't work on IE", but no vanilla javascript to show how it does work on IE (supposedly a "security feature"?), perhaps report it as a bug to MS too (if they would count it as such), so that it gets fixed in any newer release)
Like mentioned in another answer, a post on the jquery forum
if ($.browser.msie) {
$('#file').replaceWith($('#file').clone());
} else {
$('#file').val('');
}
But jquery have now removed support for browser testing, jquery.browser.
This javascript solution also worked for me, it is the vanilla equivalent of the jquery.replaceWith method.
document.getElementById("clear").addEventListener("click", function () {
var fileopen = document.getElementById("fileopen"),
clone = fileopen.cloneNode(true);
fileopen.parentNode.replaceChild(clone, fileopen);
}, false);
On jsfiddle
The important thing to note is that the cloneNode method does not preserve associated event handlers.
See this example.
document.getElementById("fileopen").addEventListener("change", function () {
alert("change");
}, false);
document.getElementById("clear").addEventListener("click", function () {
var fileopen = document.getElementById("fileopen"),
clone = fileopen.cloneNode(true);
fileopen.parentNode.replaceChild(clone, fileopen);
}, false);
On jsfiddle
But jquery.clone offers this [*1]
$("#fileopen").change(function () {
alert("change");
});
$("#clear").click(function () {
var fileopen = $("#fileopen"),
clone = fileopen.clone(true);
fileopen.replaceWith(clone);
});
On jsfiddle
[*1] jquery is able to do this if the events were added by jquery's methods as it keeps a copy in jquery.data, it does not work otherwise, so it's a bit of a cheat/work-around and means things are not compatible between different methods or libraries.
document.getElementById("fileopen").addEventListener("change", function () {
alert("change");
}, false);
$("#clear").click(function () {
var fileopen = $("#fileopen"),
clone = fileopen.clone(true);
fileopen.replaceWith(clone);
});
On jsfiddle
You can not get the attached event handler direct from the element itself.
Here is the general principle in vanilla javascript, this is how jquery an all other libraries do it (roughly).
(function () {
var listeners = [];
function getListeners(node) {
var length = listeners.length,
i = 0,
result = [],
listener;
while (i < length) {
listener = listeners[i];
if (listener.node === node) {
result.push(listener);
}
i += 1;
}
return result;
}
function addEventListener(node, type, handler) {
listeners.push({
"node": node,
"type": type,
"handler": handler
});
node.addEventListener(type, handler, false);
}
function cloneNode(node, deep, withEvents) {
var clone = node.cloneNode(deep),
attached,
length,
evt,
i = 0;
if (withEvents) {
attached = getListeners(node);
if (attached) {
length = attached.length;
while (i < length) {
evt = attached[i];
addEventListener(clone, evt.type, evt.handler);
i += 1;
}
}
}
return clone;
}
addEventListener(document.getElementById("fileopen"), "change", function () {
alert("change");
});
addEventListener(document.getElementById("clear"), "click", function () {
var fileopen = document.getElementById("fileopen"),
clone = cloneNode(fileopen, true, true);
fileopen.parentNode.replaceChild(clone, fileopen);
});
}());
On jsfiddle
Of course jquery and other libraries have all the other support methods required for maintaining such a list, this is just a demonstration.
For obvious security reasons you can't set the value of a file input, even to an empty string.
All you have to do is reset the form where the field or if you only want to reset the file input of a form containing other fields, use this:
function reset_field (e) {
e.wrap('<form>').parent('form').trigger('reset');
e.unwrap();
}
Here is an exemple: http://jsfiddle.net/v2SZJ/1/
This works for me.
$("#file").replaceWith($("#file").clone());
http://forum.jquery.com/topic/how-to-clear-a-file-input-in-ie
Hope it helps.
In IE8 they made the File Upload field read-only for security. See the IE team blog post:
Historically, the HTML File Upload Control () has been the source of a significant number of information disclosure vulnerabilities. To resolve these issues, two changes were made to the behavior of the control.
To block attacks that rely on “stealing” keystrokes to surreptitiously trick the user into typing a local file path into the control, the File Path edit box is now read-only. The user must explicitly select a file for upload using the File Browse dialog.
Additionally, the “Include local directory path when uploading files” URLAction has been set to "Disable" for the Internet Zone. This change prevents leakage of potentially sensitive local file-system information to the Internet. For instance, rather than submitting the full path C:\users\ericlaw\documents\secret\image.png, Internet Explorer 8 will now submit only the filename image.png.
$("#control").val('') is all you need! Tested on Chrome using JQuery 1.11
Other users have tested in Firefox as well.
I got stuck with all the options here. Here's a hack that I made which worked:
<form>
<input type="file">
<button type="reset" id="file_reset" style="display:none">
</form>
and you can trigger the reset using jQuery with a code similar to this:
$('#file_reset').trigger('click');
(jsfiddle: http://jsfiddle.net/eCbd6/)
I ended up with this:
if($.browser.msie || $.browser.webkit){
// doesn't work with opera and FF
$(this).after($(this).clone(true)).remove();
}else{
this.setAttribute('type', 'text');
this.setAttribute('type', 'file');
}
may not be the most elegant solution, but it work as far as I can tell.
I have used https://github.com/malsup/form/blob/master/jquery.form.js, which has a function called clearInputs(), which is crossbrowser, well tested, easy to use and handles also IE issue and hidden fields clearing if needed. Maybe a little long solution to only clear file input, but if you are dealing with crossbrowser file uploads, then this solution is recommended.
The usage is easy:
// Clear all file fields:
$("input:file").clearInputs();
// Clear also hidden fields:
$("input:file").clearInputs(true);
// Clear specific fields:
$("#myfilefield1,#myfilefield2").clearInputs();
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (re.test(t) || tag == 'textarea') {
this.value = '';
}
else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
}
else if (tag == 'select') {
this.selectedIndex = -1;
}
else if (t == "file") {
if (/MSIE/.test(navigator.userAgent)) {
$(this).replaceWith($(this).clone(true));
} else {
$(this).val('');
}
}
else if (includeHidden) {
// includeHidden can be the value true, or it can be a selector string
// indicating a special test; for example:
// $('#myForm').clearForm('.special:hidden')
// the above would clean hidden inputs that have the class of 'special'
if ( (includeHidden === true && /hidden/.test(t)) ||
(typeof includeHidden == 'string' && $(this).is(includeHidden)) )
this.value = '';
}
});
};
The value of file inputs is read only (for security reasons). You can't blank it programatically (other than by calling the reset() method of the form, which has a broader scope than just that field).
I was able to get mine working with the following code:
var input = $("#control");
input.replaceWith(input.val('').clone(true));
I have been looking for simple and clean way to clear HTML file input, the above answers are great, but none of them really answers what i'm looking for, until i came across on the web with simple an elegant way to do it :
var $input = $("#control");
$input.replaceWith($input.val('').clone(true));
all the credit go's to Chris Coyier.
// Referneces
var control = $("#control"),
clearBn = $("#clear");
// Setup the clear functionality
clearBn.on("click", function(){
control.replaceWith( control.val('').clone( true ) );
});
// Some bound handlers to preserve when cloning
control.on({
change: function(){ console.log( "Changed" ) },
focus: function(){ console.log( "Focus" ) }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="control">
<br><br>
Clear
The .clone() thing does not work in Opera (and possibly others). It keeps the content.
The closest method here for me was Jonathan's earlier, however ensuring that the field preserved its name, classes, etc made for messy code in my case.
Something like this might work well (thanks to Quentin too):
function clearInput($source) {
var $form = $('<form>')
var $targ = $source.clone().appendTo($form)
$form[0].reset()
$source.replaceWith($targ)
}
I have managed to get this to work using the following...
function resetFileElement(ele)
{
ele.val('');
ele.wrap('<form>').parent('form').trigger('reset');
ele.unwrap();
ele.prop('files')[0] = null;
ele.replaceWith(ele.clone());
}
This has been tested in IE10, FF, Chrome & Opera.
There are two caveats...
Still doesn't work properly in FF, if you refresh the page, the file element gets re-populated with the selected file. Where it is getting this info from is beyond me. What else related to a file input element could I possible try to clear?
Remember to use delegation on any events you had attached to the file input element, so they still work when the clone is made.
What I don't understand is who on earth thought not allowing you to clear an input field from an invalid unacceptable file selection was a good idea?
OK, don't let me dynamically set it with a value so I can't leach files from a user's OS, but let me clear an invalid selection without resetting an entire form.
It's not like 'accept' does anything other than a filter anyhow and in IE10, it doesn't even understand MS Word mime types, it's a joke!
On my Firefox 40.0.3 only work with this
$('input[type=file]').val('');
$('input[type=file]').replaceWith($('input[type=file]').clone(true));
its works for me in every browser.
var input = $(this);
var next = this.nextSibling;
var parent = input.parent();
var form = $("<form></form>");
form.append(input);
form[0].reset();
if (next) {
$(next).before(input);
} else {
parent.append(input);
}
I tried with the most of the techniques the users mentioned, but none of they worked in all browsers. i.e: clone() doesn't work in FF for file inputs.
I ended up copying manually the file input, and then replacing the original with the copied one. It works in all browsers.
<input type="file" id="fileID" class="aClass" name="aName"/>
var $fileInput=$("#fileID");
var $fileCopy=$("<input type='file' class='"+$fileInput.attr("class")+" id='fileID' name='"+$fileInput.attr("name")+"'/>");
$fileInput.replaceWith($fileCopy);
$("input[type=file]").wrap("<div id='fileWrapper'/>");
$("#fileWrapper").append("<div id='duplicateFile' style='display:none'>"+$("#fileWrapper").html()+"</div>");
$("#fileWrapper").html($("#duplicateFile").html());
This works with Chrome, FF, and Safari
$("#control").val("")
May not work with IE or Opera
Make it asynchronous, and reset it after the button's desired actions have been done.
<!-- Html Markup --->
<input id="btn" type="file" value="Button" onchange="function()" />
<script>
//Function
function function(e) {
//input your coding here
//Reset
var controlInput = $("#btn");
controlInput.replaceWith(controlInput = controlInput.val('').clone(true));
}
</script>
function clear() {
var input = document.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('value', '');
input.setAttribute('id', 'email_attach');
$('#email_attach').replaceWith( input.cloneNode() );
}
it does not work for me:
$('#Attachment').replaceWith($(this).clone());
or
$('#Attachment').replaceWith($('#Attachment').clone());
so in asp mvc I use razor features for replacing file input.
at first create a variable for input string with Id and Name and then use it for showing in page and replacing on reset button click:
#{
var attachmentInput = Html.TextBoxFor(c => c.Attachment, new { type = "file" });
}
#attachmentInput
<button type="button" onclick="$('##(Html.IdFor(p => p.Attachment))').replaceWith('#(attachmentInput)');">--</button>
An easy way is changing the input type and change it back again.
Something like this:
var input = $('#attachments');
input.prop('type', 'text');
input.prop('type', 'file')
You can replace it with its clone like so
var clone = $('#control').clone();
$('#control').replacewith(clone);
But this clones with its value too so you had better like so
var emtyValue = $('#control').val('');
var clone = emptyValue.clone();
$('#control').replacewith(clone);
It's easy lol (works in all browsers [except opera]):
$('input[type=file]').each(function(){
$(this).after($(this).clone(true)).remove();
});
JS Fiddle: http://jsfiddle.net/cw84x/1/
What?
In your validation function, just put
document.onlyform.upload.value="";
Assuming upload is the name:
<input type="file" name="upload" id="csv_doc"/>
I'm using JSP, not sure if that makes a difference...
Works for me, and I think it's way easier.