Search code examples
csstouchmobile-websitehtml-framework-7

How to remove highlighted text on Framework7 mobile web app when touch/tap on other elements?


For some reason, when I highlight text in the mobile web version of a Framework7 app and touch on other places I expect the highlight to be gone... it's being retained. However, on desktop web, when I highlight text and click somewhere else, the highlight is gone.

How can I make the mobile web behave like the desktop web when highlighting a text?

I tried to preventDefault on touchstart hoping it would prevent the default retention or events... but it could be something else I'm missing/not getting because with or without preventDefault it's still the same issue.

$('.content').on('touchstart', function(e) {
   e.preventDefault();
});

Thanks a lot!


Solution

  • To clear all selections upon touchstart:

    $(window).on('touchstart', function(){
        window.getSelection().removeAllRanges()
    })
    

    Edit: To only clear the selection if tapped outside of the current highlight, check to make sure the touch position doesn't fall in any selection client rects:

    $(window).on('touchstart', function(e){
        var selection = window.getSelection();
        var tappedOnSelection = selection.rangeCount && Array.from(selection.getRangeAt(0).getClientRects()).some(function(rect){
            return e.clientX >= rect.left && e.clientX <= rect.right && e.clientY >= rect.top  && e.clientY <= rect.bottom;
        });
        if(!tappedOnSelection){
            selection.removeAllRanges();
        }
    })
    $(window).on('touchend', function(e){
        e.preventDefault();
    })