How To Write A Function That Puts Text In A Paragraph - javascript

I have to create a second button/input box on the page, underneath the green paragraph square where the text has to appear. How do I write the function to get the text centered in the paragraph? I have to use document.getElementById to get the input box object and the paragraph object. Here is what I have so far:
HTML:
</head>
<body>
<div>
<button onclick="sayMagicWord();">Press For Magic </button>
</div>
<p></p>
<div>
<input id ="inputbox" type ="text" size ="10" value="Enjoy your semester at Fordham"/>
<button onclick="enjoy();">Click To Place Text In Paragraph </button>
</div>
CSS:
p {
width: 200px;
height: 200px;
background-color: green;
margin-left: 20px
}
JS:
function sayMagicWord() {
alert("PLEASE");
}
function enjoy() {
}
And here are the instructions from my prof if this makes it clearer:
On the HTML page, add a paragraph with a green background and a width and height 200px X 200px below the first button on the page. (Use a separate css file for styling the paragraph by id )
On the HMTL page, create an input box and another button side-by side and below the paragraph
Associate a second function with the new button. On the javascript file page, create that function. Inside that function, take the text from the input box and place it centered inside the paragraph ( Make use of css also). Give the paragraph and input box an id
Use document.getElementById command to get the input box object, and the paragraph object
Then assign the value of the textbox entry to the innerHTML of the paragraph

So, you need to set an id for the paragraph first. Lets say <p id='e'> </p> , though you can name it whatever you want. Then, in your javascript file, you can tap into the document, then get the ID of the paragraph (in this case, e) and use the method innerHTML() to set the paragraph to the value of the textbox
This would be:
function enjoy() {
document.getElementById('e').innerHTML = 'value here';
}
As for the CSS, refer to
https://www.w3schools.com/csS/css_align.asp
Try to look at pages like w3schools guide on things like the document object model, or its methods. As its homework, some research would go a long way.

Related

Div innerText loses new lines after setting display to none

While programming a custom WYSIWYG HTML based editor I came to this strange behavior.
jsfiddle
One enters some text containing new lines in a div, which has contentEditable set to true.
At that moment div.innerText contains exactly the entered text including the new lines.
Then one sets div.style.display = none and re-checks the div.innerText: it is the same text, but the new lines are removed.
Why is that? Is there "standard behavior" for this case?
(Tested in both FF Developer Edition 89.0b3 (64-bit) and Chrome Version 90.0.4430.85 (Official Build) (64-bit))
=> Follow up
There is also another similar strange problem:
var d = document.getElementById("divTest")
function setup() {
d.innerText = "1\n2"
}
function log() {
console.log(d.innerText)
logChildren()
}
function logChildren() {
console.log("Child nodes: ");
d.childNodes.forEach(node => {
console.log(node.toString());
});
}
div[contenteditable] {
border: 1px solid red;
}
<div contenteditable="true" id="divTest"></div>
<input type="button" value="setContent" onclick="setup()"/>
<input type="button" value="log" onclick="log()"/>
Click on the setContent button and then on log button. The output is as expected:
1
2
[object Text]
[object HTMLBRElement]
[object Text]
Then click inside the input div. Press enter after the 2 to go to a new line, and press 3. One gets
1
2
3
in the div and one would expect to get the same in the div.innerText, but it is unfortunately:
1
2
3
Child nodes:
[object Text]
[object HTMLBRElement]
[object HTMLDivElement]
[object HTMLDivElement]
Why would 1 be a [object Text] but 2 and 3 [object HTMLDivElement] ? Why would there be empty line between 1 and 2? etc. ...
It does not make any sense to me.
The implementation of innerText depends on whether or not the element is visible. As #Nisala noted in the comments, if you set the display attribute of the div back to block, the innerText contains your newline characters again.
const input = document.querySelector("#input");
function performExperiment() {
console.log(`innerText before style change: ${input.innerText}`);
input.style.display = "none";
console.log(`innerText after first style change: ${input.innerText}`);
input.style.display = "block";
console.log(`innerText after second style change: ${input.innerText}`);
}
#input {
border: 1px solid black;
}
<p>Enter multiple lines of text into the box below, then click the button</p>
<div id="input" contenteditable="true"></div>
<button onclick="performExperiment()">Experiment</button>
If we have a look at the innerText documentation, we see the first step of the behavior for the getter is defined as follows:
If this is not being rendered or if the user agent is a non-CSS user agent, then return this's descendant text content.
Note: This step can produce suprising results, as when the innerText getter is invoked on an element not being rendered, its text contents are returned, but when accessed on an element that is being rendered, all of its children that are not being rendered have their text contents ignored.
So when our div is not being rendered, we should expect that innerText returns the textContent of our div. Indeed, that is what we see.
const input = document.querySelector("#input");
function performExperiment() {
input.style.display = "none";
console.log(`innerText: ${input.innerText}`);
console.log(`textContent: ${input.textContent}`);
}
#input {
border: 1px solid black;
}
<p>Enter multiple lines of text into the box below, then click the button</p>
<div id="input" contenteditable="true"></div>
<button onclick="performExperiment()">Experiment</button>
So why are the newlines present in our innerText when the div is visible? The documentation continues:
Let results be a new empty list
For each child node node of this:
Let current be the list resulting in running the inner text collection steps with node. Each item in results will either be a string or a positive integer (a required line break count).
In this case, innerText is ignoring textContent and is instead operating on the childNodes list. Let's see what the value of that is for our div:
const input = document.querySelector("#input");
function performExperiment() {
input.childNodes.forEach(node => {
console.log(node.toString());
});
}
#input {
border: 1px solid black;
}
<p>Enter multiple lines of text into the box below, then click the button</p>
<div id="input" contenteditable="true"></div>
<button onclick="performExperiment()">Experiment</button>
As you can see, pressing the ENTER key adds a newline to the content of our div by adding a div to the childNodes list of our div. Why this is the case is outside the scope of this question, but would make for a good question on its own.
If you're working on an in-page editor, the HTML spec has a section containing best practices.
To recap:
If the div is visible, the innerText getter uses the textContent property of the div.
If the div is not visible, the inner text collection steps are followed for each node in the childNodes tree and the results are concatenated together.
When computing the value of innerText for our div, the value of the display attribute matters because it determines whether the textContent property or the evaluation of the childNodes tree will be used.
Note: There's a little more information in this answer by #Domino.

Add only changes in content (don't replace all content) to live-preview (with jQuery)

Imagine a preview feature where every time something is typed in an editable <div> box, its content is displayed in a preview <div>box. Minimum example:
jQuery('div#edit').keyup(function() {
var a = jQuery(this).html();
jQuery('div#preview').html(a);
});
#edit {
border: solid 1px #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contentEditable="true" id="edit">Type here...</div>
<div id="preview"></div>
This example replaces the entire #preview-content with the entire #edit-content. Instead of replacing everything, I would like to only add/remove those specific characters that are different.
Meaning, when the content is fetched at a key stroke and stored in the variable a, I'd like to compare a to the content of the preview box
and filter out only the differences between them.
Then I want these differences added to the preview box (at the correct locations in the already existing preview string).
Is this possible?

How to insert div/span tags into textarea using javascript?

I have a textarea in my html file and some lines of text is added to it by my .js file. I want the lines to be in different colors. So I want to wrap these lines in span/div tags (in order to set the different colors for each line) and insert them to my textarea.
My textarea is:
<textarea class="history" cols="150" rows="5" readonly="true"></textarea>
and my .js code is:
var div = document.createElement('div');
div.setAttribute("color", "green");
div.innerHTML = "hi! there";
document.querySelector(".history").appendChild(div);
When I run this code, I can see that the div is appended under the textarea html code. But I don't see the text ("hi! there") and my div in the textarea of the page.
Can anybody help me?
Use the contenteditable attribute
<p contenteditable="true">
<h1>This is a paragraph.</h1>
It is editable. Try to change this text.
</p>
appendChild function appends the element after the target element.
To put content inside of element, use innerHTML as you did with the div.

change html p tag text according to a clicked button

I have a
image with id = "b1" and html p tag that shows a number or a text
When the user click the image I want to see the value of its second parameter (here it is 1) added to the p tag inner html
Lets say p is first shown as HELLO, after clicking the image it should be shown as HELLO1
I used this code for the image
<img src="images/b_1.png" id="b1" onclick="buttonaction(this,1);"></img>
And the script is as follows
function buttonaction(id,imported){
id.src="images/b_3.png";
document.getElementById("main_display").innerhtml+=imported;
};
This did not work. I am new to this and look forward some explanation as well.
function buttonaction(id,imported){
id.src="images/b_3.png";
document.getElementById("main_display").innerHTML+=imported;
};
should work for you

Write inside text area with Javascript

I am trying to write something in text area when I click on a link.
function writeText(txt){
document.getElementById("writeArea").innerHTML = txt;
}
I would like to pass html tag in place of txt as parameter to this function so that I can get image, link etc inside text area. Is it possible in Javascript? || JQuery will be good?
Pre-thanks.
Or if jquery tag was there for a reason:
$('#writeArea').val(txt);
You should use value:
document.getElementById("writeArea").value = txt;
If you want to render some images and anchor tags on the screen then don't use a textarea. Use any other container like <div>, <span>, <p> etc.
$("#yourelementid").html(yourtext);
will put the text (in your case HTML) inside the element with id yourelementid
HTML
<p id="para1"></p>
jQuery
var txt = "<a href='http://www.google.com'>Google</a>";
$("#para1").html(txt);
See a working sample
You can easily do it in jQuery if you just want to set the text of a textarea:
$("#yourid").val("hello");
See it working: http://jsfiddle.net/quQqH/
If you're looking to have HTML in it then it needs to be a container element (such as a div).
// Html
<div id="yourid"></div>
//JavaScript
$("#yourid").html('My link');
Otherwise, another option is to have a Rich Text Editor (like Yahoo Editor) so that it renders the HTML that's in the textarea input - this will make it user editable. This is slightly more complicated, as you'll need to include the correct files to make the editor work. Then just do something like the following:
var myEditor = new YAHOO.widget.SimpleEditor('yourid', {
height: '200px',
width: '350px',
toolbar: 0 // Hides the toolbar
});
myEditor.render();
$("#yourid").val("Click for <a href='http://yahoo.com'>Yahoo</a>");
You can see this working: http://jsfiddle.net/quQqH/1/. In this case, I've removed the toolbar by setting it to 0 but it is customisable to show different buttons, etc. Just remove that line to display the default toolbar.
just give like this
$("#ID").val("<img src='images/logo.png' />");
If you want to write long text in the textarea, you can use this way:
HTML
<textarea id="theId"></textarea>
jQuery
var a = 'Test textarea content. Google" ';
$("#theId").val(a);
JS FIDDLE

Categories

Resources