javascript – Ignore click when selecting

Question:

The handler hangs on the main element. When clicking on elements inside main , if the element (click target) is a descendant of the message block, the checked class is added / removed to the corresponding message block.

In this way, you can mark messages, for example, for deletion.

But here 's the problem : if I highlight the text of a message, it counts as a click and the message is highlighted. I want that when selecting text in the message block or its descendants (for example, body ), the message block is not isolated with the checked class.

That is, if I click on any content of the message block, then the message block is selected (by the class), and if I select the text in the message block, then nothing should happen.

function hasClass(element, cls) {
  return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}

document.querySelector('.main').addEventListener('click', function(e) {
  var found = false;
  for (var i = 0; i < e.path.length; i++) {
    var elm = e.path[i];
    if (hasClass(elm, 'message')) {
      found = true;
      break;
    }
  }

  if (!found) {
    return;
  }

  if (hasClass(elm, 'checked')) {
    elm.classList.remove('checked');
  } else {
    elm.classList.add('checked');
  }

});
.message {
  background: yellow;
}

.checked {
  background: red;
}
<div class="main">
  <div class="message">
    <div class="body">Lorem ipsum, qwerty! Если текст выделен - цвет не должен переключиться</div>
  </div>
</div>

JsFiddle

Answer:

For a solution, you can check that if some text is selected, then exit the handler.

This can be determined using the isCollapsed property of the Selection object, which is returned by the getSelection () function .

For instance:

function hasClass(element, cls) {
  return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}

document.querySelector('.main').addEventListener('click', function(e) {
  if (!getSelection().isCollapsed) return;
  var found = false;
  for (var i = 0; i < e.path.length; i++) {
    var elm = e.path[i];
    if (hasClass(elm, 'message')) {
      found = true;
      break;
    }
  }

  if (!found) {
    return;
  }

  if (hasClass(elm, 'checked')) {
    elm.classList.remove('checked');
  } else {
    elm.classList.add('checked');
  }

});
.message {
  background: yellow;
}

.checked {
  background: red;
}
<div class="main">
  <div class="message">
    <div class="body">Lorem ipsum, qwerty! Если текст выделен - <span>клик</span> отменен</div>
  </div>
</div>
Scroll to Top