How do I make text bold after the user clicks a button? - javascript

I am trying to make a text editor in JavaScript and it has various features like bolding the text and italics and some others. When the user clicks on any one of them, then anything that they have selected will become edited accordingly. Now I am able to get the selected text and even put strong tags before and after the text but when I do it the text doesn't get bold only the tags are seen. How can make the text bold? I sorry but I am unable to provide code since its too much and too messy. Thanks for reading query! Also if you know any JavaScript library which could help me solve this problem then you can suggest me.
document.getElementById("button").addEventListener("click",
() => {
let text = document.getElementById("text").innerText
let selection = window.getSelection();
let boldText = "<strong>" + selection + "</strong>"
document.getElementById("text").innerText = text.replace(selection, boldText)
})
<div id="text">
The dog barks and runs around.
</div>
<button id="button">Make selected text bold</button>
I am using inner text instead of inner html in order to reproduce the problem

You are using innerText to replace which is wrong as we want to change html so use innerHTML.
Code:
document.getElementById("button").addEventListener("click",
() => {
let text = document.getElementById("text").innerText
let selection = window.getSelection();
let boldText = "<b>" + selection + "</b>"
document.getElementById("text").innerHTML = text.replace(selection, boldText) //use innerhtml instead of innertext
})
<div id="text">
The dog barks and runs around.
</div>
<button id="button">Make selected text bold</button>

Here is some code that I used to change to inputted text on a button click
<input type="text" id="sign" value="">
<p style = "font-family: 'Dancing Script', cursive; font-size:50px;"
id="signOutput"></p>
<button onclick="signFunction()">Output Signature</button>
<script>
function signFunction() {var x = document.getElementById("sign").value;
document.getElementById("signOutput").innerHTML = x;
}
</script>

<p id="mypar">Hello</p>
<br>
<button type="button" onclick="changeStyle()">Click Me</button>
<script>
function changeStyle(){
var element = document.input
var element = document.getElementById("mypar");
element.style.fontWeight = "bold";
}
</script>

Related

How to wrap with <p> in first line of contenteditable div

I used below code to wrap <p> instead of <div>.
document.execCommand('defaultParagraphSeparator', false, 'p')
But I still can't wrap first line, like this "aaa".
<div id=“body-text” class=“body-text” contenteditable=“true” data-placeholder=“Body Contents">
aaa
<p>bbb</p>
<p>ccc</p>
</div>
Does anyone know how to wrap first line "aaa" with <p>?
postscript
I changed my cord using one of the answer for reference.
But now I cant type any letter. Only if I press enter first, it works. But after I press enter and make <p>, I cant type any letter again.
Where is the problem?
<div id='body-text' class='body-text' contenteditable=true data-placeholder='Body Contents' onkeydown={firstLine}></div>
<script>
firstLine(e) {
if(e.keyCode == '13') {
var div = document.getElementById('body-text')
var text = div.firstChild.textContents
div.removeChild(div.firstChild)
var p = document.createElement('p')
p.textContent = text
div.insertBefore(p, div.firstChild)
}
}
</script>
I'm using element.firstChild to select the "aaa" textNode, and creating the paragraph element which then gets prepended back into .body-text.
var pElement = document.createElement('p');
var bodyText = document.querySelector('.body-text');
var firstLine = bodyText.firstChild;
pElement.appendChild(firstLine);
bodyText.prepend(pElement);
console.log(bodyText.outerHTML)
<div class="body-text" contenteditable="true" data-placeholder="Body Contents">
aaa
<p>bbb</p>
<p>ccc</p>
</div>
note: you don't need a class and an ID... choose one
Ok, first I have to let you know that the code you provided was using those fancy quotes “ and ” you must use either this " or this '. Having said that, I have made a Snippet that uses formatBlock.
Highlight the text and click the button <p/>.
It can wrap text in a <p>, <div>, <blockquote>, <h1>, etc..
SNIPPET
<div id="body-text" class="body-text" contenteditable="true" data-placeholder="Body Contents">
aaa
<p>bbb</p>
<p>ccc</p>
</div>
<input type="button" class="p" onclick="document.execCommand('formatBlock', false, 'p')" value="<p/>" title="Insert a Paragraph Wrapped on Highlighted Text">
One way to do it is to get first text node of your div, save the text, remove that node and then create a p tag with the text from your ancient node and insert it in your div.
UPDATED
you had a little typpo problem var text = div.firstChild.textContents, there is no s it only var text = div.firstChild.textContent
see fiddle: https://jsfiddle.net/2rgLzkyj/
HTML :
<div id='body-text' class='body-text' contenteditable=true data-placeholder='Body Contents'>
aaa
<p>bbb</p>
</div>
Javascript:
var div = document.getElementById('body-text')
div.addEventListener('keydown', onKeyDown);
function onKeyDown(e) {
if (e.keyCode == '13') {
var text = div.firstChild.textContent;
div.removeChild(div.firstChild);
var p = document.createElement('p');
p.textContent = text;
div.insertBefore(p, div.firstChild);
}
}

Taking a HTML form <input> value and using it to modify a <p> tag with Javascript

I am fairly new to Javascript and am trying to create a simple madlib application where a user can input a word through an HTML page and have that word appear in a paragraph tag when the user clicks the "submit" button. I am having troubles displaying the word that the user inputs. I know that I am close but for the life of me cannot figure out what I am missing.
Here is the HTML I am using:
<form>
<label>Word</label><input id="word"></input>
<input type="submit" value="submit" id="submitButton"></input>
</form>
<p id="story"> A {userWord goes here} is now part of the story </p>
And the Javascript:
var word = document.getElementById('word').innerHTML,
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
replaceStory(word);
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
Here is a JSFiddle: https://jsfiddle.net/5c4j2opc/
I have made a new JSFiddle: https://jsfiddle.net/5c4j2opc/3/ which works.
I changed type="submit" to type="button" to stop the page refreshing when the button is clicked and moved the word variable to the replaceStory function so it doesn't just get called once at the beginning of the script! Hope this helps.
You have to change two things.
The first is you are using innerHTML in a input element, when you want to access input element you need to get the value not the innerHTML, inputs not have this property.
The second one is that you need to pass the event on the onclick event since if you don't do it you can't cancel the submit action and then the page will be submit it automatically and reload the content. Then after you pass the event you have to apply event.preventDefault which will stop the submit for that button. Other option to avoid this problem would be possible to replace the submit button with a <button> tag or <input type="button"> since not of them will trigger the submit action.
You can see a working example https://jsfiddle.net/5c4j2opc/9/
html -> same you have
javascript
var word = document.getElementById('word'),
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(e){
replaceStory(word.value);
e.preventDefault();
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
You initialize wordjust in the beginning of the script. Besides, that the input value is not innerHTML, during that time, the value is empty.
As long as the return value is not set explicitly to false, the form will reload the page and overwrite any result.
Change your code:
var originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
var word = document.getElementById('word').value;
replaceStory(word);
return false;
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
originalStory.innerHTML = story;
};
updated fiddle
You had a couple of minor problems. The input type of the submit button should be button rather than submit. Submit does a post request and refreshes the page with the data received.
Initially you had:
var word = document.getElementById('word').innerHTML this would get the initial innerHTML which would be nothing. You have to get the inner text within word every single time the button is clicked to get the most recent text inside the textbox.
Finally, for a input node you should get .value rather than .innerHTML to get the inner text
html:
<form>
<label>Word</label><input id="word"></input>
<input type="button" value="submit" id="submitButton"></input>
</form>
<p id="story"> A {userWord goes here} is now part of the story </p>
javascript:
var word = document.getElementById('word'),
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
replaceStory(word.value);
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
I advise you to just understand Javascript first, and after then, focus on learning Jquery because it's much more easier and handy.
By the way if you want to do what you said:
You shouldn't use form tag, because you don't want to send something to server-side and you can use div tag as well instead of form tag.
<div>
<label>Word</label>
<input id="word" type="text"></input>
<button id="submitButton">Submit</button>
</div>
<span>A </span><span id="text">{here}</span><span> is now part of the story</span>
Jquery
$('#submitButton').click(function(){
txt = $('#word').val()
$('#text').text(txt);
});
Don't forget to import Jquery Package.
https://jsfiddle.net/softiran/gt8rr5pe/
You could also allow the user to change your story directly. I know this may not use an input tag, but it was very useful to me.
<div id="story">Once upon a time there was a man named
<p id="added" contenteditable="true" title="Click to change">
Bill</p>. He liked to eat tacos.</div>
I used this in a code that changed the name of the main character of a story into a user-selected name and allowed them to download the story. Hope this helps! All the user has to do is click the name "Bill" and they will be able to change the name to anything they want.

underline a part of text in Textarea [duplicate]

This question already has answers here:
Rendering HTML inside textarea
(7 answers)
Underlining text of a textarea
(4 answers)
Closed 8 years ago.
is it possible to underline a portion of text in control.
I did like this in jquery, but no underline is appearing. any sample code examples?
<textarea rows = "3" cols = "50" id = "TestName" ></textarea>
Jquery
var dvHTML = ''
dvHTML = '<span style=text-decoration: underline;>' + "Hello world" + '</span>';
$("#TestName").html(dvHTML);
Output i'm getting as only Hello world, tags are not getting recognized
You can use a contenteditable div.
<div contenteditable="true">I am saying <span>Hello</span></div>
Working Fiddle
You can't do that on textarea, You'll need some WYSIWYG if you need style on it.
Or you can fake user by adding div above of the textarea, and hide the textarea it self.
If you just want to underline the specific text you can use:
<textarea style="text-decoration:underline;" rows="20" cols="30" id="text">All are Welcome!!</textarea>
$("document").ready(function() {
$("#text").val($("#text").text());
$('textarea').keypress(function(e) {
$(this).css('text-decoration','none');
});
});
Demo: http://jsfiddle.net/fiddleyetu/czZWp/6/
Add double inverted commas " in style tag first and then a semicolon after divHtml = ''
This will work -
<!DOCTYPE html>
<html>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<textarea rows = "3" cols = "50" id = "TestName" style="text-decoration: underline;"></textarea>
<script>
var dvHTML = '';
dvHTML = "Hello world" ;
$("#TestName").html(dvHTML);
</script>
</body>
</html>
And to let you know the difference, the HTML that you enter inside the textarea will be its text. It will render it as text. So instead add text decoration as style of text area. And, about your original question - its not possible with textarea. See this -
Rendering HTML inside textarea
You can't do with a text area, the solution is to use an editable div.
HTML:
<div id="foo">
</div>
JS:
var dvHTML = '<span style="text-decoration: underline;">Hello world</span>';
$("#foo").html(dvHTML).click(function() {
this.contentEditable = true;
});
THE LIVE DEMO.

Get text of div

I want to get the text of the next id (the text is: "Show More").
<div id="show_more_less" onclick="Show_More_Less();">Show more</p>
function Show_More_Less() {
var str = document.getElementById('show_more_less').text;
}
I tried: .value but it doesn't work.
To get the text of an element in a cross browser way, you can do this :
var e = document.getElementById('show_more_less');
var text = e.textContent || e.innerText;
Try innerHTML:
var str = document.getElementById('show_more_less').innerHTML;
Also you have an opening <div> tag and a closing </p> tag which is inconsistent. You probably meant:
<div id="show_more_less" onclick="Show_More_Less();">Show more</div>
Should make some checks to see if childNodes[0] exists and if it's a text node, but basically:
var str = document.getElementById('show_more_less').childNodes[0].nodeValue;

jQuery find and replace string

I have somewhere on website a specific text, let's say "lollypops", and I want to replace all the occurrences of this string with "marshmellows". The problem is that I don't know where exactly the text is. I know I could do something like:
$(body).html($(body).html().replace('lollypops', 'marshmellows'));
This would probably work, but I need to rewrite as little HTML as I can, so I'm thinking something like:
search for the string
find the closest parent element
rewrite only the closest parent element
replace this even in attributes, but not all, for example replace it in class, but not in src
In example, I would have structure like this
<body>
<div>
<div>
<p>
<h1>
<a>lollypops</a>
</h1>
</p>
<span>lollypops</span>
</div>
</div>
<p>
<span class="lollypops">Hello, World!</span>
<img src="/lollypops.jpg" alt="Cool image" />
</p>
<body>
In this example, every occurrence of "lollypops" would be replaced, only <img src="... would remain the same and the only elements that would actually be manipulated would be <a> and both <span>s.
Does anybody know how to do this?
You could do something like this:
$("span, p").each(function() {
var text = $(this).text();
text = text.replace("lollypops", "marshmellows");
$(this).text(text);
});
It will be better to mark all tags with text that needs to be examined with a suitable class name.
Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.
You could do something this way:
$(document.body).find('*').each(function() {
if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
$(this).removeClass('lollypops');
$(this).addClass('marshmellows');
}
var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
var text = $(this).text(); //getting just current node text
text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
$(this).text(text); //setting text
$(this).append(tmp); //re-append 'foundlings'
});
example: http://jsfiddle.net/steweb/MhQZD/
You could do something like this:
HTML
<div class="element">
<span>Hi, I am Murtaza</span>
</div>
jQuery
$(".element span").text(function(index, text) {
return text.replace('am', 'am not');
});
Below is the code I used to replace some text, with colored text. It's simple, took the text and replace it within an HTML tag. It works for each words in that class tags.
$('.hightlight').each(function(){
//highlight_words('going', this);
var high = 'going';
high = high.replace(/\W/g, '');
var str = high.split(" ");
var text = $(this).text();
text = text.replace(str, "<span style='color: blue'>"+str+"</span>");
$(this).html(text);
});
var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);
Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.
HTML:
<div>
<div>
<p>
<h1>
<a class="swapText">lollipops</a>
</h1>
</p>
<span class="swapText">lollipops</span>
</div>
</div>
<p>
<span class="lollipops">Hello, World!</span>
<img src="/lollipops.jpg" alt="Cool image" />
</p>
jQuery:
$(document).ready(function() {
$('.swapText').text("marshmallows");
});

Categories

Resources