Working just the FIRST time only... HOW IF DESELECT SELECTED TEXT pressing again button re-selects it ...?

I have problem here that is SELECT TEXT IN div button click working just the FIRST time only… HOW IF DESELECT SELECTED TEXT pressing again button re-selects it … ???

<div id="code-pattern"></div>

    $('button#selectPatterncode').on('click', function(e) {
        selectText("code-pattern");
    });

function selectText(containerid) {
    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select();
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().addRange(range);
    }
}

Hi @mymac1, you might remove all ranges from the selection if the selection already contains the container; actually it would make sense to empty the selection anyway in case the user already selected some text inside the container, as merging ranges won’t work. For example:

function selectText (containerId) {
  var selection = window.getSelection()
  var container = document.getElementById(containerId)
  var isContainerSelected = selection.containsNode(container)
  var range = document.createRange()

  selection.removeAllRanges()

  if (!isContainerSelected) {
    range.selectNode(container)
    selection.addRange(range)
  }
}

here meaning
HOW
IF DESELECT text by pressing outside of it… then how SELECTED TEXT pressing again the button … ??? after pressing again fails re-selects it — is like button Not function… after first time select it…

well

IDK it works for me. Are there any errors in the browser console?

No error in console but…

I make this observation
after pressing again Selects it only if mouse clicked on the DIV

eg if text on the left clicked on the right **but in the DIV on the right** after pressing again fails re-selects it — is like button Not function…WHEN PRESS ABOVE OR BELOW THE DIV in other words Not pressing on the div itself...

well

BTW I am using jQuery Mobile and its swipe functionality…

console chrome

VM134 content.min.js:2 [Deprecation] Element.createShadowRoot is deprecated and will be removed in M73, around March 2019. Please use Element.attachShadow instead. See https://www.chromestatus.com/features/4507242028072960 for more details.

No error in console but…

I make this observation
after pressing SELECT BUTTON again TEXT Selected it only if mouse clicked before (to deselect it) on the containing DIV

after pressing again fails re-selects it — is like button Not function…WHEN PRESS ABOVE OR BELOW THE DIV in other words NOT pressing on the CONTAINING div itself…
well

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.