Reputation: 13
Hello I am new with JavaScript trying to find solution for my problem. Is there any way I can live highlight my text like we do in PDF's ?
Something like this: Plunker
<div class="box">
llentesque volutpat tempus eleifend. Integer viverra erat ante. Aliquam
gravida ac nibh non sollicitudin.
</div>
<button type="button">highlight</button>
I have a button which allow/enable text highlighting on click. Then I drag my mouse selecting texts will get yellow background color.
Is this possible ? Any example will really help. Thanks
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) { });
.box span {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MainCtrl">
<div class="box">llentesque volutpat tempus eleifend. Integer viverra erat ante. Aliquam gravida ac nibh non sollicitudin.</div>
<button type="button">highlight</button>
<div class="box" style="margin-top:100px">
DEMO:
<br>llentesque volutpat tempus eleifend. Integer viverra erat ante. <span>Aliquam gravida ac nibh non sollicitudin.</span>
</div>
</div>
Upvotes: 1
Views: 134
Reputation: 3053
The Stack Overflow entry covers numerous methods for highlighting text on a page using javascript:
How to highlight text using javascript
If this isn't what you wanted, comment below.
Upvotes: 1
Reputation: 10021
here's a quick example that I made for you to play with. Basically you want some sort of event, I think on('input')
works well here, and then check to see if there is a <span>
element somewhere.
This is not a complete example of course, and could use some more work, but it should get you started.
$('#textarea').on('input', function() {
var text = $('#textarea').val();
$('#result').html(text);
if ($('#result').html().indexOf('<span>') > -1) {
$('span:not(.highlighted)').addClass('highlighted');
}
});
// Set the value initially and trigger the event.
$('#textarea').val('Hello <span>World</span>.').trigger('input');
textarea {
width: 196px;
height: 100px;
}
#result {
border: 1px solid gray;
width: 200px;
height: 200px;
overflow: scroll;
}
.highlighted {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id='textarea'></textarea>
<div id='result'></div>
Upvotes: 1