1

Possible duplicate: Change CSS of selected text using Javascript

I tried the code from above link but not getting the result for iPad browser to highlight the selected text.

function makeEditableAndHighlight(colour) {
    var range, sel = window.getSelection();
    if (sel.rangeCount && sel.getRangeAt) {
        range = sel.getRangeAt(0);
    }
    document.designMode = "on";
    if (range) {
        sel.removeAllRanges();
        sel.addRange(range);
    }
    // Use HiliteColor since some browsers apply BackColor to the whole block
    if (!document.execCommand("HiliteColor", false, colour)) {
        document.execCommand("BackColor", false, colour);
    }
    document.designMode = "off";
}

function highlight(colour) {
    var range, sel;
    if (window.getSelection) {
        // IE9 and non-IE
        try {
            if (!document.execCommand("BackColor", false, colour)) {
                makeEditableAndHighlight(colour);
            }
        } catch (ex) {
            makeEditableAndHighlight(colour)
        }
    } else if (document.selection && document.selection.createRange) {
        // IE <= 8 case
        range = document.selection.createRange();
        range.execCommand("BackColor", false, colour);
    }
}

It works flawlessly in desktop browser like safari, chrome. But in case of iPad safari browser, the way of selection is not similar to text selection as in any desktop browser and I am not getting the outcome to highlight the text.

enter image description here

My simple HTML code is:

     <div><h1>Introduction </h1></div>

     <div>          
            <p>This is an example: </p>
            <p>in other paragraph.</p> 
            <p>one more paragraph  </p>

            <button type="button" onclick="highlight('yellow')">Click Me!</button>
     </div>  

Please suggest if any changes need to be made or any other api needs to be included.

Community
  • 1
  • 1
Satish
  • 1,315
  • 4
  • 15
  • 22

1 Answers1

2

You've to trigger the highlight-function via touchend-event (and + click for desktop support):

jQuery

$('button').on('click touchend', function() {
    highlight('yellow');
});

Fiddle

yckart
  • 32,460
  • 9
  • 122
  • 129
  • Which iOS-version do you use? – yckart Dec 18 '12 at 09:33
  • ya thanks it is working, in older version of jquery it was not supported. I have to dowload the new jquery library 1.8.3. .Earlier i was using jquery 1.6.4 which does not support it. – Satish Dec 18 '12 at 10:07
  • 1
    @Terry yeah, the `on`-event handler isn't supported in versions earlier then 1.7. (For jQuery < 1.7 you can use `.bind` instead). – yckart Dec 18 '12 at 10:23
  • 1
    You might also find [this post](https://stackoverflow.com/questions/3303469/does-mousedown-mouseup-in-jquery-work-for-the-ipad) as helpful as I did. iPhones seem to disable any javascript related to a user highlighting text - using .bind() with touchstart and touchend solved the problem. – Leopold Mc Jan 08 '19 at 16:26