user16032281
user16032281

Reputation:

Highlighting text with jquery

I am creating a test and I want a highlighter feature so that students can highlight important points while reading a paragraph. I am using jquery for this and my code is

$('.panel-one').on('mouseup',function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
        
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;

    }
    console.log(text);
})

I want to create a button (floating with cursor after selection) to highlight the selected text which is coming out on the console for which I have to wrap the text with a div. and also delete the highlight (removing the div) using the same method.

here is the website which is using this exact same feature (creating the same type of test). I don't want different color but highlighting and deleting highlighting https://ieltsonlinetests.com/ielts-mock-test-2021-january-reading-practice-test-1

I do try it with .wrap and wrapping the "text" variable but no luck.

if you need any other info pls let me know

Upvotes: 1

Views: 80

Answers (1)

2pha
2pha

Reputation: 10165

Here is how far I got before getting bored..

// Button
const but = document.getElementById('hightlight-button');
but.addEventListener('click', (e) => {
  // Check if something is selected.
  if (window.getSelection().toString().length) {
    but.style.display = 'none';
    // Create a span to insert
    var span = document.createElement('span');
    span.classList.add('hightlighted');
    let selection = window.getSelection();
    let range = selection.getRangeAt(0);
    // Insert the selected text into the new span.
    span.textContent = selection.toString();
    // Remove the text.
    range.deleteContents();
    // Insert the span text.
    range.insertNode(span);
  }
})

// highlight event listener.
document.addEventListener('mouseup', (e) => {
    // Check if something is selected.
  if (window.getSelection().toString().length) {
  
    let selection = window.getSelection();
    let range = selection.getRangeAt(0);
    let selectionRect = range.getBoundingClientRect();
    // Position the button.
    but.style.left = selectionRect.x+'px';
    but.style.top = selectionRect.y+selectionRect.height+'px';
    // Show the button
    but.style.display = 'block';
  }
  else {
    but.style.display = 'none';
  }
})
#hightlight-button {
  position: absolute;
  display: none;
}

.hightlighted {
  background-color: #ff0000;
  cursor: not-allowed; 
}
<div>
thisfsghtesting text.
this is some tesfghng text.
this is some testing text.
this is svb testing text.
this is some testing text.
this is some testcvbn text.
this is some testing text.
</div>

<button id="hightlight-button">
hightlight
</button>

Upvotes: 1

Related Questions