Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overrides the native behavior when selecting texts on mobile device

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?

like image 437
Cybrix Avatar asked Jun 28 '12 01:06

Cybrix


2 Answers

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)

like image 110
David Mulder Avatar answered Oct 12 '22 02:10

David Mulder


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');
        });
    }
});
like image 32
arttronics Avatar answered Oct 12 '22 01:10

arttronics