JQuery line numbers on Textarea with wrapping support - javascript

I am working on a textarea with line numbers. Now I found a great little script. http://jakiestfu.github.io/Behave.js/
Demo here: http://jakiestfu.github.io/Behave.js/examples/example-hook-linenums.html
The one feature I am missing is the ability to enable line wrapping.
Of course I can add wrap="on" to the textarea, and that indeed offers wrapping, but the line numbers are then messed up.
Any idea how I could add support for wrapping whist keeping the line numbers correct?

Try this:
<!DOCTYPE html>
<html>
<body onload="keyDown()">
<div class="container" style="width:300px;">
<div id="numbers" style="float:left; background:gray; width:20px;"></div>
<textarea onkeypress="keyDown()" rows="1" style="line-height:20px; display:block; float:right; overflow:hidden;" id="ta"></textarea>
</div>
<script type="text/javascript">
function keyDown(){
var taLineHeight = 20; // This should match the line-height in the CSS
var taHeight = ta.scrollHeight; // Get the scroll height of the textarea
ta.style.height = taHeight + "px"; // This line is optional, I included it so you can more easily count the lines in an expanded textarea
var numberOfLines = Math.floor(taHeight/taLineHeight);
var inner= "";
for(var i=1; i<=numberOfLines; i++)
inner += "<div>"+i+"</div>";
document.getElementById("numbers").innerHTML = inner;
}
</script>
</body></html>

Related

Is there a way to stop html from making line breaks when a tag is in another tag?

So I would like to make a calculator with some formatting to make it look nice. It keeps making a new line for my p tag and I don't want it to, is there any fix for this?
var n1 = document.getElementById("n1");
var n2 = document.getElementById("n2");
var display = document.getElementById("disp");
function addAndDisplay() {
display.innerHTML = (Number(n1.value)+Number(n2.value)).toString();
}
<!DOCTYPE html>
<html>
<head>
<title>Addition</title>
</head>
<body>
<h1>Addition</h1>
<h3>Value one:</h3>
<input type="number" id="n1">
<h3>Value two:</h3>
<input type="number" id="n2">
<br>
<button onclick="addAndDisplay()">Add</button>
<h3>The output: <p id="disp">You have not calculated anything yet</p>.</h3>
</body>
</html>
EDIT: Thanks #Pipe and #Pointy I appreciate your help a lot!
Per default, a paragraph is a block level element. This means that it starts on a new line and takes up the full width. Maybe you should consider using something else.
For this kind of usecase, you would want to use <span></span>. Span is using display: inline which allows multiple inline-elements to appear next to each other.
It might be useful to read this article about the CSS display property - it will help you understand the suggested solution much better.
you shuld use span instead of p. p is paragraph element and span can be used to group elements for styling purposes
var n1 = document.getElementById("n1");
var n2 = document.getElementById("n2");
var display = document.getElementById("disp");
function addAndDisplay() {
display.innerHTML = (Number(n1.value)+Number(n2.value)).toString();
}
p{
display:inline-block;}
<!DOCTYPE html>
<html>
<head>
<title>Addition</title>
</head>
<body>
<h1>Addition</h1>
<h3>Value one:</h3>
<input type="number" id="n1">
<h3>Value two:</h3>
<input type="number" id="n2">
<br>
<button onclick="addAndDisplay()">Add</button>
<h3>The output: <p id="disp">You have not calculated anything yet</p>.</h3>
</body>
</html>

Javascript - Repeated use of a function without it removing previous instances?

How would I repeat the output of a function, without it affecting previous instances outputs of the function?
For some context:
I am creating a text editor and have created a "link-maker" which creates an relative href link.
However, when I append the link to the text area content, the link displays perfectly for the first instance. Yet, if I repeat that function to add another relative link, it removes the html wrapping the first link appended.
I have tried changing the text output of the link to getElementByClassName, as I thought that the ID would only be best used for a sole function which would not need to be repeated. Where as by using the class it allows for more general use.
Some code for example:
<textarea name="textarea" class="txtarea" id="textarea" style="display: none; font-family: Arial;"></textarea>
<iframe name="editor" id="editor" style="width:824; height: 400; font-family: Arial;"></iframe>
function bcmllink() {
var logicalid = document.getElementById("logicalid");
var txtinput = document.getElementById("txtinput");
var txtOutput = document.getElementById("txtOutput");
var name = logicalid.value;
txtOutput.value = "\x3ca href\x3d\x22\x23\x22 bcmltype\x3d\x22link\x22 logicalid\x3d\x22" + logicalid.value + "\x22\x3e" + txtinput.value + "\x3c\x2fa\x3e"
}
function appendtotext() {
var myTextArea = $('.txtarea');
myTextArea.val(editor.document.getElementsByTagName('body')[0].innerHTML = editor.document.getElementsByTagName('body')[0].
textContent + txtOutput.value + " ")
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<textarea name="textarea" class="txtarea" id="textarea" style="display: none; font-family: Arial;"></textarea>
<iframe name="editor" id="editor" style="width:824; height: 400; font-family: Arial;"></iframe>
<div id="bcml">
<h3>BCML Links</h3>
<form action="">
<fieldset class="bcml_links">
<label>Enter your logical id</label><input type="number" id="logicalid" class="left5"/><br><br>
<label>Enter your text</label><input type="text" id="txtinput" class="left5"/><input class="left5" type="button" value="Generate" onClick="bcmllink()" /><br><br>
<input type="text" style="width : 600;" id="txtOutput" /><br><br>
<b>Copy and paste this text into your source view</b>
<input type="button" value="append" onClick="appendtotext()"/>
</fieldset>
</form>
Maybe you should consider using lists instead of textarea. Im currently using this for a chatapp im creating and it doesnt remove the previous messages when i recieve a new one.
You are already importing jquery. Why not make use of its .text() function?
$('textarea#textarea').text("<a href='ok'>Click here</a>");
Note, that you will not have to worry about formatting HTML or escaping characters.
If you want to append to a previously filled textarea: you would do something like:
var old_text = $('textarea#textarea').text();
$('textarea#textarea').text(old_text + "<a href='ok'>Click here</a>");
I managed to find the answer to what I was looking for:
function appendtotext() {
var myTextArea = $('.txtarea');myTextArea.val(editor.document.getElementsByTagName('body')[0].innerHTML = editor.document.getElementsByTagName('body')[0].
innerHTML + txtOutput.value + " ")}
The issue was that I was previously using textContent on the last line (where innerHTML now sits). This meant that with each instance of the function being used, it was removing the surrounding html tags and placing in only the text content.
See here for further information:
https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent

Move element created to textarea

I would like to link the 2 scripts to send the result of the first to the clipboard, using the second script. Both work but separately
Thank you, sorry if I am not clear.
<html>
<body>
<p>Click the button to create a h1 element with some text.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var h = document.createElement("H1");
var t = document.createTextNode("It works");
h.appendChild(t);
document.body.appendChild(h);
}
</script>
<script type="text/javascript" src="ZeroClipboard.js">
</script>
<textarea name="box-content" id="box-content" rows="10" cols="70">
Will be copied to clipboard.
Line2.
Line3.
</textarea>
<br /><br />
Simply by changing .value of textarea:
document.getElementById('box-content').value = "It works";
You can not place a tag in textArea tag.
The <textarea> tag defines a multi-line text input control.A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier).The size of a text area can be specified by the cols and rows attributes, or even better; through CSS' height and width properties.
HTML textarea
Instead you can place text only in areatag.
function myFunction() {
//var h = document.createElement("H1");
var t = document.createTextNode("It works");
//h.appendChild(t);
document.getElementById('box-content').appendChild(t);
}
myFunction();
<textarea name="box-content" id="box-content" rows="10" cols="70"></textarea>

Controlling the text size in the canvas (textarea)

I want to create a canvas that displays text from textarea.
I have a problem with controlling the size of the text in textarea.
In other words, I want the user to choose the size of the text then write it in the text area which in turn will be displayed on the canvas once the button is clicked.
I tried this code but there is a problem i do not what is it.
Here is a sample of the code:
<script>
var y = 30;
function pasteText()
{
Text=document.getElementById('textarea').value;
var x = 30;
var lineheight = 15;
var lines = Text.split('\n');
$("#clr2 font").click(function (){
context.fillStyle=$(this).css("color");
});
$("#clr3 font").click(function (){
context.font=$(this).css("font-size")+ "Arial";
});
for (var i = 0; i<lines.length; i++)
context.fillText(lines[i], x, y + (i*lineheight) );
y+=38;
}
</script>
<body>
<canvas class="canvas" id="canvas" width="600" height="200" style="border:1px solid"> </canvas>
<font id="clr3">
<font style="font-size:9pt;"> Small</font>
<font style="font-size:16pt;"> Medium</font>
<font style="font-size:24pt;"> Large</font>
</font>
<textarea name="textarea" cols="72" rows="6" id="textarea" value="Type the text here" ></textarea>
<input type="button" name="paste" value="Paste on the canvas" onClick="pasteText()"/>
<script type="text/javascript">
var container = layer2.parentNode;
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
</script>
</body>
I am sure that the problem is in context.font
because context.font accepts the size and the family of the font.
I am not sure if what I wrote in my code is the correct syntax
context.font=$(this).css("font-size")+ "Arial";
You have quite a lot of problems in your code, some that pop immediately:
The for loop code in not enclosed in braces { }
The click handlers are defined inside the pasteText function and thus will only be registered after the user clicked the paste text button.
the <font> tags are not standart tags and some browsers, especially IE won't like it.
update:
Is it possible that what's missing is a space between the font size and the font face? try to add a space before the Arial:
context.font=$(this).css("font-size")+ " Arial";

How do I make an expanding textbox?

I want to make a textbook where it starts out as a given width/height. Then if users type more then the given amount of space, the textbox expands downward. How do I go about doing this? Do I use CSS?
The basic textbox just displays a scroll bar when users pass the number of rows allow. How do I make it so the textbox expands the rows by say 5 more?
<form method="post" action="">
<textarea name="comments" cols="50" rows="5"></textarea><br>
<input type="submit" value="Submit" />
</form>
How do I use the example that Robert Harvey mentioned? I never used JavaScript before..
jQuery AutoResize Plugin
http://james.padolsey.com/javascript/jquery-plugin-autoresize/
Steps to use:
You need jQuery. To add it to your page:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
Then, download the plugin and put it in the same folder as your web page. To reference it, add this to your web page:
<script type="text/javascript"
src="autoresize.jquery.js"></script>
Next, add a textbox to your page:
<textarea id="comment" style="width: 400px; padding: 10px; height: 50px;
display: block; font-family:Sans-serif; font-size:1.2em;">
Type something in here, when you get close to the end the box will expand!
</textarea>
Finally, in a script block, add the code that hooks up the plugin to the textbox:
<script type="text/javascript">
$('textarea#comment').autoResize({
// On resize:
onResize : function() {
$(this).css({opacity:0.8});
},
// After resize:
animateCallback : function() {
$(this).css({opacity:1});
},
// Quite slow animation:
animateDuration : 300,
// More extra space:
extraSpace : 40
});
</script>
You can add a library if you care to, or just keep track of the textarea's scrollTop property.
If scrollTop is not zero, add your rows.
<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title>Expand textarea </title>
<style>
textarea{overflow-y:scroll}
</style>
<script>
onload=function(){
var who=document.getElementsByName('comments')[0];
who.onkeyup=function(){
if(who.scrollTop)who.rows=parseInt(who.rows)+5;
}
}
</script>
</head>
<body>
<textarea name="comments" cols="50" rows="5"></textarea>
</body>
</html>
Here is my solution using only vanilla javascript.
Tested to work in Chrome, Firefox & IE8 and up.
On load, or whack it in a function:
var element = document.getElementById('comments');
var retractsAutomatically = false;
var sizeOfOne = element.clientHeight;
element.rows = 2;
var sizeOfExtra = element.clientHeight - sizeOfOne;
element.rows = 1;
var resize = function() {
var length = element.scrollHeight;
if (retractsAutomatically) {
if (element.clientHeight == length)
return;
}
else {
element.rows = 1;
length = element.scrollHeight;
}
element.rows = 1 + (length - sizeOfOne) / sizeOfExtra;
};
//modern
if (element.addEventListener)
element.addEventListener('input', resize, false);
//IE8
else {
element.attachEvent('onpropertychange', resize)
retractsAutomaticaly = true;
}
CSS & HTML:
textarea#comments { overflow:hidden; }
<textarea id="comments" cols="50" rows="1"></textarea>

Categories

Resources