I would like to know if there is a way to overrides the native behavior when you select texts on mobile browser. I am trying to support both iPhone and Android devices by providing my own action bar.
Any tips?
Although you could quite simply use the selectionchange
event to show your 'actionbar' alongside the native functionality, if you would want to 'replace' the native behavior you would need to either fake the entire selections from scratch or use the selectionchange
event and the second the the selection is made you wrap the selected text with a coloured span element for example and cancel the real selection (whilst showing your actionbar), the trouble with this method would be that 1) the native actionbar might show for a split second and 2) the experience will be different from what the user is used to possibly having dangerous effects. If on the other hand you would want to do the selections from scratch you should use the user-select
css property to disable text selection and next figure out based on the touchstart and thouchend which text to 'select' (with coloured spans) (realistically only possible in an extremely controlled environment (for example a text-only reader application)).
Please note that this will not work in Firefox and Opera as the selectionchange
event is not fired there and you would need to use a touchend
event handler on the document + stopping bubbling of all other touchend events to support opera mobile and firefox mobile. (Credit for the fact that select
doesn't work and selectionchange
should be used goes to Tim Down)
Reference:
jsFiddle Demo with Plugin
The above jsFiddle Demo I made uses a Plugin to allow you to prevent any block of text from being selected in Android or iOS devices (along with desktop browsers too).
This does not interfere with other markup you may have, such as jQuery .click();
event listeners as demonstrated in the jsFiddle.
It's easy to use and here is the sample markup once the jQuery plugin is installed.
Sample HTML:
<p class="notSelectable">This text is not selectable</p>
<p> This text is selectable</p>
Sample jQuery:
$(document).ready(function(){
$('.notSelectable').disableSelection();
});
Complete jQuery Plugin:
$.fn.extend({
disableSelection: function() {
this.each(function() {
this.onselectstart = function() {
return false;
};
this.unselectable = "on";
$(this).css('-moz-user-select', 'none');
$(this).css('-webkit-user-select', 'none');
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With