JQuery highlight not working properly - javascript

Reference
I am trying to build a form with the functionality something similar to word search.
I have a text-area and a series of divs with contents. When a user types a word or a sentence, the words that match with the div contents are highlighted in yellow and when text-area content is removed or emptied, highlighting is also removed.
The sample that I made highlights the words but doesn't highlight it completely. Only first character is highlighted. And when I try to search for a new word, previously highlighted words are still highlighted.
HTML
<textarea id="my_ta" name="my_ta"></textarea>
<hr>
Similiar Words
<hr>
<div>
This is a serious question
</div>
<div>
Does this question ring a bell inside your head?
</div>
<div>
This question is a question about questions
</div>
CSS
.highlight { background-color: yellow }
JavaScript
$(document).ready(function(){
$('#my_ta').keypress(function()
{
var value = $(this).val();
if(value)
{
$('div').highlight(value);
}
else
{
$('.highlight').removeHighlight();
}
});
});
FIDDLE

Looking at the documentation, seems that you'de be good to go just with
$(document).ready(function(){
$('#my_ta').on('input',function(){
$('div').removeHighlight().highlight($(this).val());
});
});
Use input or keyup instead of keypress.
http://jsfiddle.net/2vsgbmgz/3/

Rather use Regular Expressions. It's easier to find anything you're looking for.
HTML
<div>
You can have any text inside a <div>
or any valid html tag you want.
</div>
CSS
#highlight {
background-color: red
}
jQuery
function highlight() {
$.each($('div'), function() {
//-------------------------Get Text
var str = $(this).html();
//-------------------------Wrap Matching Text
str = str.replace(/hi/ig, '<span id="highlight">$&</span>');
//-------------------------Insert Coloured Text
$(this).html(str);
});
}
highlight();
jsFiddle

Related

Make substring uneditable within larger div string, while also preserving the unique substring CSS (distinct from rest of text styling in div)

Setup:
Below is a tweet example appearing as an editable text:
"First words of tweet, #tweetaddress last words of tweet"
Requirement and Problem:
I'd like the user to be able to edit the text, but NOT change the #tweetaddress, which I have working. However, I also would like the #tweetAddress to be color:blue while the rest of the text is color:white. I can achieve this result initially through the use of a span wrapped around the #tweetaddress. (shown is code below.)
I'm fine on JavaScript detecting if the #tweetaddress has changed. BUT...
The problem:
...if the user starts typing right next to the #tweetaddress, the styling from the 'never-change' class applies to all the new text. Is there a way to limit my to only include the #tweetaddress, so that all new text into the div is outside it and not blue?
I've tried initially putting different spans on either side of the #tweetaddress 'never-change' span, but if the user deletes the characters in the other spans and then retypes, the new letters still come out blue.
I'd really love to hear any ideas on how I could proceed.
HTML
<div contenteditable id="text-input" placeholder="Tweet text here">First words of tweet,<span class="never-change">#tweetaddress</span> last words of tweet</div>
CSS:
.never-change{
color:blue;
}
JS:
$('#text-input').keydown(function() {
textStart = $(this).html();
tweetAddress = '#tweetaddress';
}
$('#text-input').keyup(function() {
textEnd = $(this).text();
if (textEnd.indexOf(placeholderText) > -1){
return false;
} else {
alert("Twiiter name. Cannot edit");
$(this).html(textStart);
}
Thank you in advance.

Rearrange DOM elements according to given standard

I will try do describe the issue:
I'm using contenteditable to edit text in DIV. The standard for elements I need to have in that DIV is:
paragraph:
<p style="someStyles"><span style="someStyles">TEXT GOES HERE</span></p>
empty line:
<p style="someStyles"><span style="someStyles"><br></span></p>
Due to some user text manipulations like copy/paste standard is messed in that DIV like here (ex. of case):
<span style="someStyles">
<p style="someStyles">SOME TEXT HERE</p>
<p style="someStyles">SOME TEXT HERE</p>
</span>
Im looking for a solution that will take messed text elements and rearrange it to given standard I wrote about above, any suggestions ?
After rearranging elements it should look like this:
<p style="someStyles">
<span style="someStyles">SOME TEXT HERE</span>
<span style="someStyles">SOME TEXT HERE</span>
</p>
P.S - I want to make that rearrange function on keyup event while typing and only for whole p element that caret is on.
As I stated in my comment, I can't see a general solution to this, but your specific example could be solved like this. And you can easily make several other conversions based on this one.
The replace function is based on this answer.
// this converts an element to another tag
function replace(thisWith, that) {
$(thisWith).replaceWith(function() {
var i, replacement = $('<' + that + '>').html($(this).html());
for (i = 0; i < this.attributes.length; i++) {
replacement.attr(this.attributes[i].name, this.attributes[i].value);
}
return replacement;
});
}
function convert() {
// get SPANs that has Ps inside
var $spans = $("#content span").has("p");
$spans.each(function () {
// change children Ps into SPANs
replace($(this).children("p"), "span");
// change parent SPAN into P
replace(this, "p");
});
}
Here is a test jsfiddle.

Jquery - how to copy selected text from div tag?

lets say I have two DIVS in the page. #news div and #imp div respectively.
<div id="news">
Apple is facing a lawsuit for not telling users about the amount of memory required by an upgrade its flagship operating system.
</div>
<div id="imp">
<!-- Empty -->
</div>
Now my requirement is if I select only 'Apple' from the whole sentence then that selected portion gets copied and pasted into div #imp. And if copied, other portions then get appended.
Could you do something like this?
$( document ).ready(function() {
$('#news').mouseup(function (e){
text = window.getSelection().toString();
$('#imp').append(text);
});
});
Hope this helps.
JS Bin: http://jsbin.com/xabije/edit?html,js,output
I would copy the marked text, using this library, into clipboard
https://code.google.com/p/liveclipboard-jquery/
and use jquery to insert to the div imp
Scott Duke beat me to it but the point was to append so I changed html to append and added a space so the words don't jumble together:
$('#news').mouseup(function (){
var selectedText = window.getSelection().toString();
$('#imp').append(" "+ selectedText)
});
FIDDLE

Input field with attached text to the right

I'm doing a fancy comment list on my project, structured like this:
As you see, there's a comments list and at his bottom there's an input field (textarea) to submit a comment. Note that there's the current username attached to the right (let's call it a simple static appended text).
I just found this little JS to make an input field resize automatically by adapting it to the content.
function resizeInput() {
$(this).attr('size', $(this).val().length);
}
$('input[type="text"]').keyup(resizeInput).each(resizeInput);
But it's not enough. I need it for a textarea and I want it to behave correctly when a comment is long enough to wrap on another line. By definition, the input field is a box, and it obviously acts badly compared to what I want:
Instead, this should be the right behavior:
I looked everywhere and I can't think any way to implement this. Can somebody help me?
Here is a good plugin for textarea. But it using jQuery.
usage simple as always.
$(document).ready(function(){
$('textarea').autosize();
});
You could use the contenteditable attribute:
<span contenteditable="true">comment</span> by <span class="userName">someone</span>
It is supported in practically all browsers. Using the right CSS, you can underline the content and also limit the width.
I think you mean this
NOTE: No check for selection and bound to document. Exercise for the reader to bind to a specific field and swap it for a span
FiDDLE
$(document).keypress(function(e) {
var char = String.fromCharCode(e.which);
if (e.which==13) char = '<br/>'; // needs to handle backspace etc.
$("#textfield").append(char);
$("#hiddenfield").val($("#textfield").text()); // or .html if you want the BRs
e.preventDefault();
});
using
<span id="textfield"></span> - by My Username
If you make the field contenteditable you will get this in Chrome so some additional CSS may be needed
Use a <span> with contenteditable (supported in IE too). Here is a fiddle: http://jsfiddle.net/goabqjLn/2/
<span contenteditable>Insert a comment...</span> by My Username
Then, using JavaScript, attach an event listener that mirrors the inner text of the span into a hidden input field, so it gets submitted with your <form>.
Edit: I have updated the fiddle to also include the JS code. Here is the updated code:
<span class="editor" id="editor" contenteditable data-placeholder="Insert a comment...">Insert a comment...</span> by My Username
<!-- Hide this textarea in production: -->
<textarea type="text" id="comment"></textarea>
And the JS:
function mirror() {
var text = $('#editor').html().trim()
.replace(' ', ' ')
.replace(/<br(\s*)\/*>/ig, '\n') // replace single line-breaks
.replace(/<[p|div]\s/ig, '\n$0') // add a line break before all div and p tags
.replace(/(<([^>]+)>)/ig, ""); // remove any remaining tags
$('#comment').val(text);
}
$('#editor').focus(function () {
var editor = $(this);
if (editor.text() == editor.attr('data-placeholder')) {
editor.text('');
}
}).blur(function () {
var editor = $(this);
if (editor.text() == editor.attr('data-placeholder')) {
editor.text(editor.attr('data-placeholder'));
}
}).blur(mirror).keyup(mirror);

jQuery remove() or after() causing whitespace to be removed

I have the following html:
<p>This is some random text in a paragraph with a <span class="blue">blue</span> word.</p>
<p>This is some random text in a paragraph with a <span class="blue">blue</span> <i>word</i>.</p>
<p>This is some random text in a paragraph with a <span class="blue">blue</span> <span class="blue">word</span>.</p>
My CSS is as follows:
.blue{
color:blue;
}
.popup{
background-color:lightblue;
}
And finally my JS:
var popup = false;
$(".blue").click(function(){
if (!popup){
$(this).after("<div class='popup'>This is some popup text</div>");
popup = true;
}
else{
$(".popup").remove();
popup = false;
}
});
Now my problem, when I call the remove function on my popup class it removes whitespace between tags
As explained in some answers below, the after function could also be causing this.
. eg:
<span class="blue">blue</span> <i>word</i>
becomes
<span class="blue">blue</span><i>word</i>
It does not do this when the text following a blue class is not in tags eg:
<span class="blue">blue</span> word
Why does this happen and how can I prevent it?
For further reference here is a fiddle: http://jsfiddle.net/6fqDq/
Edit: It seems this problem is localized to Chrome as it does not occur in FF or IE.
The reason this is happening is because you added a block element(div), the block element breaks into a new line, then when it's removed, it takes away the whitespace with it that's after it, because for HTML a whitespace and a newline is pretty much the same.
You have several solutions, some were mentioned here :
Use &nbsp
Put a space inside the <i> tag instead of between tags, so <i> word</i> would work fine.
Use a <span> tag instead of a div tag on the after.
I don't think the problem is with remove but with after in this case which probably ignore text node and therefore ignoring the white space. If you use append, also it does place the element somewhere else the problem disappear.
http://jsfiddle.net/6fqDq/8/
var popup = false;
$(".blue").click(function() {
if (!popup) {
$(this).append("<div class='popup'>This is some popup text</div>");
popup = true;
} else{
$(".popup").remove();
popup = false;
}
});
Not sure why it does it. But a quick fix would be to put the white space within the <i> tag. Like this:
<p>This is some random text in a paragraph with a <span class="blue">blue</span><i> word</i>.</p>
See http://jsfiddle.net/6fqDq/5/
just add
<p>This is some random text in a paragraph with a <span class="blue">blue</span> <span class="blue">word</span>.</p>
Use .append instead of .after()
if (!popup){
$(this).append("<div class='popup'>This is some popup text</div>");
popup = true;
}
I can't explain why it doesn't work with .after, but i think it could be appending on the whitespace
DEMO
Not sure why it is happening, but maybe replace your spaces with entities? is a space. You could do it with javascript str.replace('> <', '> <' ) or in php str_replace('> <', '> <', str)

Categories

Resources