how to remove highlight from only one selection using mark.js

Viewed 205

I've created a form that highlights matching text on entered in a textarea on the page as you make selections on the checkboxes. It seems to work properly when you are checking the checkboxes, but as soon as you have more then one checkbox checked and then uncheck a single checkbox, all highlights get removed. I would like it to only remove the highlight of the unchecked box when it is changed from checked to unchecked.

I'm fairly new to JavaScript so I'm not sure if I'm missing something obvious here or not but I am stumped as to why I'm getting this behavior.

Here is an example function handling the highlight on a single checkbox. You can see my full code in the JS fiddle link here: https://jsfiddle.net/gosem01/kf8az926/1/

function highlightArrowsOnCheck() {
  var instanceArrows = new Mark(highlightedParagraph);
  var options = {
    "debug": true,
    "log": window.console
  };

  if (checkedArrows.checked) {
    instanceArrows.markRegExp(/\«|»/g, options);
  } else {
    instanceArrows.unmark(options);
  }
}

mark.js docs: https://markjs.io/

1 Answers

Use className parameter to mark/unmark a group

https://markjs.io/#parameters

function highlightArrowsOnCheck() {
  var instanceArrows = new Mark(highlightedParagraph);
  var options = {
    "className": "arrows", // added
    "debug": true,
    "log": window.console
  };

  if (checkedArrows.checked) {
    instanceArrows.markRegExp(/\«|»/g, options);
  } else {
    instanceArrows.unmark(options);
  }
}

Working Demo

Note: togglecheckall function is simplified by triggering event programmatically.

Related