How to get highlighted words and wrap it in new element with data-attribute?


Tags: javascript,jquery,html,css,html5-data

Problem :

JSFIDDLE

HTML:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet est tempus, fermentum ligula et, hendrerit nisl. Praesent tempor eget quam quis auctor. Vivamus mollis mauris id sem aliquam, vel fermentum neque fringilla. Morbi malesuada accumsan augue ut hendrerit. Aenean commodo vulputate lacinia. Integer at purus eget arcu venenatis consectetur vel sed sem. Mauris quis est id ligula aliquam tempor a nec neque. Donec scelerisque velit ac metus aliquet, in euismod nisl lacinia. Quisque imperdiet gravida facilisis. In hac habitasse platea dictumst. Quisque vel erat congue, consequat libero eget, blandit sapien. Suspendisse potenti. Praesent at mollis purus.</p>

CSS:

.highlight {
  color: red;
}

JS:

$(function(){

  $('p').click(function(){
    // get highlighted words

    // get user input
    var user_input = window.prompt();

    // put highlighted words in <span class="highlight"></span> element
    // and add data-id to the span element
    // expected output:
    // <p>... <span class="highlight" data-id="user input here">highlighted words here</span> ...</p>
  });

});

I have a block of text in p tag and I want it to be like this:

  1. User select some word(s) inside the block
  2. User enter something inside the prompt box
  3. Put the highlighted word(s) inside span tag with data-attribute (I'd called it data-id) and this data-attribute value is coming from the prompt (step 2 above)

How do I achieve this?

Please help me.



Solution :

With the help of fiddle given in the comment you can achieve it as below:

function selectHTML() {
  try {
    if (window.ActiveXObject) {
      var c = document.selection.createRange();
      return c.htmlText;
    }

    var nNd = document.createElement("span");
    var w = getSelection().getRangeAt(0);
    w.surroundContents(nNd);
    return nNd.innerHTML;
  } catch (e) {
    if (window.ActiveXObject) {
      return document.selection.createRange();
    } else {
      return getSelection();
    }
  }
}

$(function() {
  $('p').click(function() {
    var selected = selectHTML();
    var user_input = window.prompt();
    $('span').addClass('highlight').attr('data-id', user_input);
  });
});
.highlight {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet est tempus, fermentum ligula et, hendrerit nisl. Praesent tempor eget quam quis auctor. Vivamus mollis mauris id sem aliquam, vel fermentum neque fringilla. Morbi malesuada accumsan
  augue ut hendrerit. Aenean commodo vulputate lacinia. Integer at purus eget arcu venenatis consectetur vel sed sem. Mauris quis est id ligula aliquam tempor a nec neque. Donec scelerisque velit ac metus aliquet, in euismod nisl lacinia. Quisque imperdiet
  gravida facilisis. In hac habitasse platea dictumst. Quisque vel erat congue, consequat libero eget, blandit sapien. Suspendisse potenti. Praesent at mollis purus.</p>


    CSS Howto..

    How to center a CSS Hexagon

    How to set a fixed background with CSS?

    How to get crossing CSS borders

    How do I make a textarea resize properly when I resize browser window?

    How to print data from left to right in html using css

    How to specify a path to be followed while animating an object in HTML using CSS, JQuery

    How to fill vertical spaces between tiles in a grid system (Using CSS)

    How to use psd elements in an upload form? [closed]

    How to make my css webkit animation stop changing

    Showing responsive menu link that is not shown in regular navigation menu

    How to use a custom toggle switch in jquery mobile

    simple css issue - how to change anchor inside li if li:hover

    How to recalculate css with jQuery window resize?

    how to add embedded ruby in style tag

    How to fit HTML table row to its content

    how to get the site to not collapse with css

    HTML/CSS: how to put text both right and left aligned in a paragraph

    How to use Chrome Inspector to show the popup css for a jquery plugin

    how can I center this menu with CSS

    How to keep all the parent except the first LI highlighted when the sub LI is hovered over

    How to hide grey scrollbars on a DIV in Android - they only show when you cannot scroll

    How to include a css class that is an image on codeigniter form submit?

    How to divide in 4 equal parts a li menu

    How to hide text behind image

    How do I preload non-hardcoded background images with jQuery?

    How to align radio buttons with labels in one line? [duplicate]

    CSS dropdown submenu with dynamic width: how to align left?

    How to float

    to bottom of a

    when you can't use position:relative and position:absolute

    How to change the display property in a css class using js when user clicks a button

    How to resolve css incompabilities/differences between different versions of IE?