Need some help/pointers....
When the user will click on a p element i want it content to be displayed in an text area so it would be possible to modify the text and etc...
The text area will be of a fixed width.Thus when the last character will be at the right border it will go automatically on a lower row. In this case, in order to make a new row, should i count how many characters fit in the text area fixed width and each time this number is met to add a new row?
Also in the case that the user will break the line before it reaches the right border, should i search for a \n RegExp?(with .match()?)
I think that those 2 cases need to be is a timeInterval(setTimeout perhaps?) to check on a milliseconds basis the all typing that happens. I'm trying to do it with pure Javascript
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="p1">text text text text text text text text text text text,
text text text text text text text text text text text,
text text text text text text text text text text text,
text text text text text text text text text text text.
</p>
<div id="holder"></div>
<script type="text/javascript">
var text_to_copy = document.getElementById('p1').textContent;
//every row with a fixed text area width fits 62 characters
var input = document.createElement("textarea");
var holder = document.getElementById("holder");
document.getElementById('p1').onclick = function(){
holder.appendChild(input);
input.id = "textarea_id";
input.style.width = "412px";
input.value = text_to_copy.replace(/\s{1,}/g, ' ');
if(text_to_copy.match('\n')){
input.rows +=1;
}
/*setTimeout(function(){
if ((text_to_copy.length % 62) == 0){
input.rows += 1;
}
},300);*/
}
</script>
</body>
</html>
You can adapt the textarea height to match the scroll height using the clientHeight vs scrollHeight
Here is a working copy of your code
var text_to_copy = document.getElementById('p1').textContent;
var input = document.createElement("textarea");
var holder = document.getElementById("holder");
document.getElementById('p1').onclick = function(){
holder.appendChild(input);
input.id = "textarea_id";
input.style.width = "412px";
input.value = text_to_copy.replace(/\s{1,}/g, ' ');
//This function reset the textarea height base on his content. (when text is added/removed)
var setTextAreaHeight = function(){
input.style.height = '5px'; // Set to minimum height possible to create vertical scroll bars
input.style.height = input.scrollHeight + 'px'; // remove the scroll bars
}
//call it once
setTextAreaHeight();
//attach to changes/key pressing.
input.onkeydown = setTextAreaHeight;
input.onkeyup = setTextAreaHeight;
input.onchange = setTextAreaHeight;
};
<p id="p1">text text text text text text text text text text text,
text text text text text text text text text text text,
text text text text text text text text text text text,
text text text text text text text text text text text.
</p>
<div id="holder"></div>
Related
I have a requirement where I have to highlight the appropriate button based on the format of the word selected in the textarea.
For instance,
If i have a text inside the textarea like, I am a new _text area_.
and if user clicks on the word _text area_ or brings the cursor point over that text the button bold should be highlighted, as the word is enclosed within _ .
I tried to use onclick event to get the index and traverse the string using regex .However it doesn't seem to work.Could anyone suggest me how to do this?
var getFormat = function(event) {
var element = document.getElementById('editor');
console.log('editor', element);
var startIndex = element.selectionStart;
console.log('startIndex', startIndex);
var selectedText = element.value.slice(startIndex);
var stringMatch = selectedText.match(((\ * )\ 2)(.* ? )\ 1));
console.log('stringMatch', stringMatch);
}
<html>
<body>
<textarea onclick='getFormat(event);' rows='10' cols='10' id='editor'></textarea>
<button>Bold</button>
</body>
</html>
I want to know how to change the background color or may be color of the text that was modified in a textarea.
Like suppose, consider a textarea with a pre-defined value as "Hello World".
Now if you try to change the text inside the textarea to "Hello Universe", it should show Universe highlighted (may be background color change, or color change or make it bold, anything.
I just want to get the modified text to be highlighted so it is visible what was changed.
Highlighting is possible if you make the textarea partially transparent and then had a div behind it where you can clone the content and put span tags around the changed values. The hard part is in figuring out how to diff the string. For an example of highlight certain parts of text "in the text area" see this fiddle:
https://jsfiddle.net/mcgraphix/tn0ahcfx/
<div class="container">
<div id="highlighter"></div>
<textarea id="editor" onkeyup="updateHighlight()"
value="This is some text in the editor"></textarea>
</div>
JS
function updateHighlight() {
//calculate index of changes
//assume chars 1-10 are different //see my comment for how to calculate what to highlight
var content = document.getElementById('editor').value;
var highlighted = '';
var i = 0;
while (i < content.length) {
if (i === 1) {
highlighted += '<span class="highlighted">';
} else if (i > 10) {
highlighted += '</span>'
}
highlighted += content.charAt(i);
i++;
}
document.getElementById('highlighter').innerHTML = highlighted;
}
Basically, as you type the text in the text area is parsed and as text is identified as being in need of highlight, a span tag is wrapped around it. After parsing the text, the copy with the spans is put inside the div that is behind the textarea. With the right css you can hide the text in that div and just put a background color such that it looks highlighted. The fiddle gives you the basic idea but you would have to account for the user resizing the text area as you need to make sure the text area and the "highlighter" behind it are aligned.
The hard part is figuring out what to highlight. such that you don't highlight every character after the first change. Take a look at Levenshtein distance algorithm for determining which characters you need to highlight when comparing two strings.
Keep old value in variable.
Split the value using delimiter as space
Check indexOf new value after spitting by space
Use Array#indexOf to listen the change in value!
Most important point, you can not apply style over characters in textarea. Example given below has a demonstration in div element considering value from textarea
var input = $('textarea');
var div = $('div');
var oldVal = input.val();
var oldArr = oldVal.split(' ');
input.on('input', function() {
var newVal = this.value;
var html = [];
newVal.split(' ').forEach(function(el) {
if (oldArr.indexOf(el) === -1) {
html.push('<span style="color:green">' + el + '</span>');
} else {
html.push('<span>' + el + '</span>');
}
});
div.html(html.join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<textarea>Hello World</textarea>
<div></div>
I'm adding some code to a text area on button click, I'd like to put the cursor in a specific point in the text area.
e.g. cursor goes here on button click
Here is the code I have currently, any help would be great.
html
div
<textarea id="editor" class="html-text" spellcheck="false"></textarea>
jquery
$(".div").click(function() {
var caretPos = document.getElementById("editor").selectionStart;
var textAreaTxt = $("#editor").val();
var txtToAdd = '<div></div>';
$("#editor").val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos));
return false;
});
Use
$("#editor").focus();
to give focus back to the textarea, and then
$("#editor")[0].setSelectionRange(selectionStart, selectionEnd);
to place the cursor.
setSelectionRange
I have a list of divs that look like below:
<div id="main1">
<span class="username">Username_1</span>
white some text content inside div...
blue some text content inside div...
yellow some text content inside div...
</div>
<div id="main2">
<span class="username">Username_2</span>
another test1 text content inside div...
another test2 text content inside div...
another text test3 content inside div...
</div>
When user highlights some text inside of these divs (for example, he highlights: 'blue some text' from main1 div or 'test2 text con' from main2) -- how to get the value of username from <span class="username>{username}</span>?
In other words, when user highlights some text from main1 div, I need to get the value: Username_1 and when he highlights some text within main2 div, I should get the value: Username_2, etc.
(if it's easier, I could add id to the span too). I can only use plain Javascript (not jQuery). Thank you.
You'll need to get the parent element of the selection, then look through the parent's children to find the first span element. That element's innerHTML will contain the text you need.
Borrowing "get selection" and "find selection's parent" code from Get parent element of a selected text and Get the Highlighted/Selected text:
function checksel() {
var txt = getSelectionText();
var parent = getSelectionParentElement();
var user = null;
if (txt && parent)
for (var i = 0; i < parent.children.length; ++i) {
var kid = parent.children[i];
if (kid.tagName.toLowerCase() == "span") {
user = kid.innerHTML;
}
}
var p = document.createElement('p');
if (user) {
p.innerHTML = "user: '" + user + "'. Text: '" + txt + "'.";
} else {
p.innerHTML = "No user or no selection.";
}
document.body.appendChild(p);
}
function getSelectionParentElement() {
var parentEl = null,
sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
parentEl = sel.getRangeAt(0).commonAncestorContainer;
if (parentEl.nodeType != 1) {
parentEl = parentEl.parentNode;
}
}
} else if ((sel = document.selection) && sel.type != "Control") {
parentEl = sel.createRange().parentElement();
}
return parentEl;
}
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
<div id="main1">
<span class="username">Username_1</span>
white some text content inside div... blue some text content inside div... yellow some text content inside div...
</div>
<div id="main2">
<span class="username">Username_2</span>
another test1 text content inside div... another test2 text content inside div... another text test3 content inside div...
</div>
<button id="check" onclick="checksel()">check</button>
To get the text selected in the page :
window.getSelection().toString()
I'll let it to your discretion to find how to use because frankly speaking, I've got no inspiration with that. But I suspect you might use it by storing the result in a var and pass it to your textform :).
My try : http://jsfiddle.net/Bladepianist/Lj4x0xks/
May be this will help.
WORKING DEMO : HERE
Note : check for null / no selection (might throw error)
Check for the JS function
HTML
<div id="main1">
<span class="username">Username_1</span>
white some text content inside div...
blue some text content inside div...
yellow some text content inside div...
</div>
<div id="main2">
<span class="username">Username_2</span>
another test1 text content inside div...
another test2 text content inside div...
another text test3 content inside div...
</div>
<button onclick="getSelectedSpan()">Get Span innerHTML</button>
JS
function getSelectedSpan() {
// get the base node of the selected text
var baseNode = window.getSelection().baseNode;
// get the nearest parent div of base node
var nearestParentDiv = baseNode.parentNode.closest("div");
// get the spans inside the div
var spanList = nearestParentDiv.getElementsByTagName("span");
// first span is what you want
console.log(spanList[0].innerHTML);
}
I am working on a ticker that loops text within the body of a div. I can get it to move the text at a specified rate but I am having trouble figuring out how to get JQuery to loop the text. Once the contents in the div have reached the end, how do I loop it back while still showing rest of the contents from the tail?
Code:
var left = -500;
$(document).ready(function(e){
function tick() {
left++;
$(".ticker-text").css("margin-left", -left + "px");
setTimeout(tick, 16);
}
tick();
});
html:
<div class = "ticker-container">
<div class = "ticker-text">
start text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text end
</div>
</div>
http://jsfiddle.net/mxu4v/1/
Just reset the margin when it gets too far left:
var width = $('.ticker-text').width(),
containerwidth = $('.ticker-container').width(),
left = containerwidth;
$(document).ready(function(e){
function tick() {
if(--left < -width){
left = containerwidth;
}
$(".ticker-text").css("margin-left", left + "px");
setTimeout(tick, 16);
}
tick();
});
Note that the CSS must be changed so that .ticker-text assumes the width of its contents, and not 1000% as you specified:
.ticker-text {
height: 150%;
white-space:nowrap;
display:inline-block;
}
Here is a demonstration: http://jsfiddle.net/fHd4Z/
Just to flesh my comment out into an answer:
As above, I believe you'd be best of using one of the pre existing frameworks designed for this. In terms of a quick knock up of the feature, you could start with something like this: http://jsfiddle.net/B9ruA/
JS:
var tickerId="#tickerText";
function tickify(e) {
var text=$(e).text().split("");
var newText="";
for (var i=0;i<text.length;i++) {
newText+="<span class='tickerChar'>" + text[i] + "</span>";
}
$(e).html(newText);
}
tickify(tickerId);
function tick(){
$(tickerId + " span.tickerChar:first").hide("slide",{direction:"left"},50,function(){$(this).appendTo($(tickerId)).show("slide",{direction:"right"},50);});
}
setInterval(function(){tick()},200);
HTML:
<div id="tickerText"> woo, here is some text for ticking, text that ticks, ticky text to test with </div>
CSS:
div.ui-effects-wrapper {
display:inline;
}
notes:
I had to add some css to stop the animated characters being displayed as block (and thus on their own line). You would probably make the selector more specific to not screw with other animations on the page (if you have any).
Obviously this could do with some timing readjustments for smoothness sake - I couldn't be bothered doing the niggly trial and error work behind that but have fun (another reason to use a framework).
in my comment I mentioned the methods slideLeft and slideRight - they don't exist. my bad.