Using the HTML <input type="url">
field is normally a good idea when you're asking the user to enter a URL. It doesn't make a huge difference on desktop browsers, but makes it a lot easier on mobile browsers. On iOS, when you've focused on a URL input field, the keyboard switches to a slightly different layout with different keys optimized for entering URLs.
This is great for things like web sign-in where you're asking the user to enter their domain name to sign in. However, for some reason, browsers have implemented the URL validation a bit too strictly. If you don't enter a URL scheme, you'll get an error like the below if you try to submit the form.
This is pretty irritating because it forces the user to enter the URL scheme http://
or https://
, which ironically on the special iOS URL keyboard, requires tapping the "123" button in order to get to the screen to type the ":" character. It would be nice if the URL field accepted plain domain names and defaulted to http://
.
I wrote a bit of JavaScript that will prepend http://
to the value of any <input type="url">
form fields on blur.
<script>
/* add http:// to URL fields on blur or when enter is pressed */
document.addEventListener('DOMContentLoaded', function() {
function addDefaultScheme(target) {
if(target.value.match(/^(?!https?:).+\..+/)) {
target.value = "http://"+target.value;
}
}
var elements = document.querySelectorAll("input[type=url]");
Array.prototype.forEach.call(elements, function(el, i){
el.addEventListener("blur", function(e){
addDefaultScheme(e.target);
});
el.addEventListener("keydown", function(e){
if(e.keyCode == 13) {
addDefaultScheme(e.target);
}
});
});
});
</script>
I wish browsers would implement this themselves, but in the mean time you can use this bit of JS to provide a bit better user experience when asking your users for URLs.
<script async>
, since some browsers (eg Chrome) may fire the DOMContentLoaded event before async scripts are loaded. Just FYI!