Only apply styling to selected text in content editable <p> - javascript

Problem
Hi, I have some code that when a button is clicked, all of the content in a contentEditable <p> tag will have a font-weight of 600 (bold).
What I'm wondering is how can I make it so when the button is pressed, rather than style all the content in the p tag to 600 font weight, only style the selected text. For example, if you only highlight the first two words of the p tag and press the button, only the first two words will have their font-weight changed.
Image example
In the example, when the button is pressed, only the first two words would have their font-weight changed.
Link to the fiddle containing code: https://jsfiddle.net/AidanYoung/9tg4oas5/

here is your solution.
function changeBold() {
const text = window.getSelection().toString();
var btn = document.createElement('span');
btn.innerHTML = text;
btn.style.fontWeight = 'bold';
document.execCommand('insertHTML', false, btn.outerHTML);
}
<p contenteditable="true" id="contenttxt">
Some text in this paragraph tag
</p>
<button onclick="changeBold()">Bold selected text</button>

You can use the span label and add ID
function changeBold() {
document.getElementById("strongC").style.fontWeight = "600";
}
<p contenteditable="true" id="contenttxt">
<span id="strongC">Some text</span>
in this paragraph tag
</p>
<button onclick="changeBold()">Bold selected text</button>

Related

Creating a read more button with html and javascript

I am using html, css and javascript to create a read more button. I have a paragraph and if this button is pressed, more text will de displayed.
This is my html code
<p class="details">Text that is displayed><span class="read-more">More text</span></p>
<button class="read-more-button">Read more</button>
//on the bottom of the page I also added the scripts
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
In my css file I make the paragraph between the span tag not visible
.details .read-more{
display:none;
}
In my javascript
const readMoreBtn = document.querySelector('.read-more-button');
const text = document.querySelector('.details');
readMoreBtn.addEventListener('click',(e)=>{
details.classList.toggle('read-more');
})
The problem is that when I press the Read more button nothing happens, the paragraph between the span tag is not displayed. Am I missing something here?
You need to target .read-more class, not .details.
Also, there is a undefined variable in event listener.
The correct JS code should be:
const readMoreBtn = document.querySelector('.read-more-button');
const text = document.querySelector('.read-more');
readMoreBtn.addEventListener('click',(e)=>{
text.classList.toggle('read-more');
})
You're toggling the class of p.details. You should toggle the class of `.read-more'.
const readMoreBtn = document.querySelector('.read-more-button');
const moreText = document.querySelector('.read-more');
readMoreBtn.addEventListener('click',(e) => {
moreText.classList.toggle('read-more');
// Consider changing the button text to collapse or removing it altogether perhaps?
})
.details .read-more{
display:none;
}
<p class="details">Text that is displayed<span class="read-more">More text</span></p>
<button class="read-more-button">Read more</button>

Create 4 (On and off) buttons, each to modify a paragraph

Create 4 buttons, each to modify a paragraph. Each button should turn on or off the changes to the paragraph on each click of the button.
1. Toggle bold button should bold the paragraph.
2. Toggle position should change the position of the paragraph
3. Toggle color will change the color
4. Toggle size will change the size.
My code till now:`
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>Click the button to bold the text of the DIV element:</p>
<p><button onclick="myFunction()">Toggle Bold</button></p>
<div id="myDIV">Hello</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.innerHTML === "Hello") {
x.innerHTML = ;
} else {
x.innerHTML = "Hello";
}
}
</script>
</body>
</html>
Now, here I do not know how to change the paragraph text to bold in this. Moreover, I have to use the event handler for 4 buttons. How can I do it?
You can use the button to toggle the bold-ness of the paragraph by toggling the font-weight style.
function myFunction() {
var div = document.getElementById("myDIV");
if (div.style['font-weight']) {
div.style.removeProperty('font-weight');
} else {
div.style['font-weight'] = 800;
}
}
<p>Click the button to bold the text of the DIV element:</p>
<p><button onclick="myFunction()">Toggle Bold</button></p>
<div id="myDIV">Hello</div>
for the handling of four buttons with one function part you can do something like this.
as you create four buttons for each paragraph. modify the onclick event like
<p><button onclick="myFunction('myDiv')">Toggle Bold</button></p>
Here you are passing the ID of the paragraph controlled by the given button to the function
and modify the event handler with a div paramter like
function myFunction(asdf) {
var x = document.getElementById(asdf);
----your function----
}

How to copy text and paste into a textarea using JS?

I am looking for a solution how to copy text and then paste a new text automatic in textarea. I found solutions, but based on jquery I'm looking for something simple on clean js.
function copyToClipboard(elementId) {
// Create a "hidden" input
var aux = document.createElement("input");
// Assign it the value of the specified element
aux.setAttribute("value", document.getElementById(elementId).innerHTML);
// Append it to the body
document.body.appendChild(aux);
// Highlight its content
aux.select();
// Copy the highlighted text
document.execCommand("copy");
// Remove it from the body
document.body.removeChild(aux);
let textarea = document.getElementById("select-this");
textarea.focus();
}
<div class="wrapper">
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<p id="p3">P3: I am a 3 paragraph</p>
<button onclick="copyToClipboard('p1')">Copy P1</button>
<button onclick="copyToClipboard('p2')">Copy P2</button>
<button onclick="copyToClipboard('p3')">Copy P3</button>
<br/><br/>
<textarea id="select-this" value="I just copied this with only JavaScript"/></textarea>
</div>
I found some solutions, but I still do not know how to make the text automatically appear in textarea after pressing the button.
append the copied value to value of textarea everytime you run copyToClipboard
function copyToClipboard(elementId) {
// Create a "hidden" input
var aux = document.createElement("input");
// Assign it the value of the specified element
aux.setAttribute("value", document.getElementById(elementId).innerHTML);
// Append it to the body
document.body.appendChild(aux);
// Highlight its content
aux.select();
// Copy the highlighted text
document.execCommand("copy");
// Remove it from the body
document.body.removeChild(aux);
let textarea = document.getElementById("select-this");
textarea.focus();
textarea.value += document.getElementById(elementId).innerHTML
}
<div class="wrapper">
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<p id="p3">P3: I am a 3 paragraph</p>
<button onclick="copyToClipboard('p1')">Copy P1</button>
<button onclick="copyToClipboard('p2')">Copy P2</button>
<button onclick="copyToClipboard('p3')">Copy P3</button>
<br/><br/>
<textarea id="select-this" value="I just copied this with only JavaScript"/></textarea>
</div>
ummm...You are REALLY over-complicating stuff...
Just use the following JS:
let textarea = document.getElementById("select-this");
textarea.focus();
function changeTextarea(elementId) {
textarea.innerHTML = document.body.querySelector(elementId).innerHTML;
}
and edit the HTML of the buttons as follows:
<button onclick="changeTextarea('#p1')">Copy P1</button>
<button onclick="changeTextarea('#p2')">Copy P2</button>
<button onclick="changeTextarea('#p3')">Copy P3</button>
You don't need to copy and then paste the values of the paragraphs to the <textarea>. Just change it using the innerHTML property...
I've a simple solution for that, just using the part of the code you have.
function copyToClipboard(elementId) {
var text = document.getElementById(elementId).innerHTML;
let textarea = document.getElementById("select-this");
textarea.innerHTML = text;
textarea.focus();
}
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<p id="p3">P3: I am a 3 paragraph</p>
<button onclick="copyToClipboard('p1')">Copy P1</button>
<button onclick="copyToClipboard('p2')">Copy P2</button>
<button onclick="copyToClipboard('p3')">Copy P3</button>
<br><br>
<textarea id="select-this" value="I just copied this with only JavaScript"/></textarea>
</div>

JavaScript execCommand("HiliteColor") unhighlight

JavaScript execCommand("HiliteColor") adds highlights really nicely by adding spans but I wanna be able to dynamically unhighlight text by checking to see if the selected text is in a span that is highlighted. Then there's the issue to wear of only half the selected text is in a span. I've tried adding the spans myself and trying to unhighlight them by:
document.getElementsByClassName('highlight').remove();
alert(window.getComputedStyle(document.getElementById("pages"), null).getPropertyValue('background-color'));
alert(document.getElementById("pages").style.backgroundColor);
Just to see if I could check the background and then highlight or if I could remove the class highlight.
My project is on codepen at: https://codepen.io/pokepimp007/pen/wxGKEQ
ANSWER
I created a function that takes a color parameter when a button is clicked. When delete highlight button is clicked it sends the parameter color "transparent":
function Highlight(color) {
document.designMode = "on";
var sel = window.getSelection();
sel.removeAllRanges();
var range = document.createRange();
range.setStart(editor.startContainer, editor.startOffset);
range.setEnd(editor.endContainer, editor.endOffset);
sel.addRange(range);
if (!sel.isCollapsed) {
if (!document.execCommand("HiliteColor", false, color)) {
document.execCommand("BackColor", false, color);
}
}
sel.removeAllRanges();
document.designMode = "off";
}
I saw you use jQuery so added the jQuery tag to your post.
This does the trick.
$('#removeHighlight').on('click', function(){
$('.highlight').each(function(){
$(this).replaceWith($(this).text());
})
})
.highlight {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is a stupid bit of text with <span class="highlight">highlight_1</span> in it to display the power of jquery to do stuff like removing <span class="highlight">highlight_2</span> in a html document. Go on and press the button to see the <span class="highlight">highlight_3</span> magic.</p>
<button id="removeHighlight">Remove</button>
If you only want to remove one highlight do this.
$('#removeHighlight').on('click', function(){
$('.highlight').first().replaceWith($('.highlight').first().text());
})
.highlight {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is a stupid bit of text with <span class="highlight">highlight_1</span> in it to display the power of jquery to do stuff like removing <span class="highlight">highlight_2</span> in a html document. Go on and press the button to see the <span class="highlight">highlight_3</span> magic.</p>
<button id="removeHighlight">Remove 1</button>
Or if you want to remove it on click
$('p').on('click', '.highlight', function(){
$(this).replaceWith($(this).text());
})
.highlight {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is a stupid bit of text with <span class="highlight">highlight_1</span> in it to display the power of jquery to do stuff like removing <span class="highlight">highlight_2</span> in a html document. Go on and press the button to see the <span class="highlight">highlight_3</span> magic.</p>

I want to change text with a button

I want to provide all my posts on my blog in 2 languages. I found a way to change the text into another language with buttons. But I can't put any images or other css styles in the text that changes. Then the buttons don't work anymore.
<button onclick="document.getElementById('chgtext').innerHTML='This is the default text. I can't put any css or html in here';">English</button>   <button onclick="document.getElementById('chgtext').innerHTML='Text changed into Another language';">Other language</button>
<div id="chgtext">This is the default text. I can't put any css or html in here</div>
Is there a way I can make something like this but with a code where I'm able to put images, font styles,... in the code?.
Or is there maybe a way to only change the text. And leave the images with multiple divs?
TEXT (changes)
IMAGE
TEXT (changes)
http://oihanevalbuenaredondo.be/2017/01/17/current-favorites-voorbeeld/ --> this is an example of a post i want in 2 languages. I need multiple images, al the text in the post needs to be changed from one language to another, with buttons
You need to iterate over all the children of your element. Using JQuery, and assuming just one level of descendants, you could use something like this...
$('#chgtxt').children().each( function() {
var oldtext = $(this).text();
if (oldtext) {
var newtext = oldtext+" CHANGED. ";
$(this).text(newtext);
}
});
You can create your own using this simple code, it simply gets an entry and replace it by it's value in the array. Ex :
var lang = {
"helloWorld": {
en: "Hello World",
fr: "Bonjour monde"
},
"mynameis": {
en: "My name is",
fr: "Mon nom est"
}
}
$(document).ready(function(){
$(body).find('.trn').each(function($elem){
var currentLang = 'en';
$($elem).html(lang[$($elem).data('trn')][currentLang]);
});
});
For each text your need to add a data with the key and a class trn, just like this.
<span class="trn" data-trn="mynameis"></span> Nicolas
Check this link for more informations
hopes it helps !
Nic
You have a single quote in the text of the first onclick "can't" which is causing the javascript to think that it is the end of the string.
You need to add a backslash "can\'t"
<button onclick="document.getElementById('chgtext').innerHTML='<p>Blue</p>This is the default text. I can\'t put any css or html in here';">English</button>  <button onclick="document.getElementById('chgtext').innerHTML='<p>Blue</p>Text changed into Another language';">Other language</button>
<div id="chgtext"><p>Blue</p>This is the default text. I can't put any css or html in here</div>
<style>
p {color:blue;}
</style>
You need to escape all quotes inside of inserted content. Have a look at snippet and try to click on buttons
<button onclick="document.getElementById('chgtext').innerHTML='This is the default text. <img src=\'http://lorempixel.com/output/nightlife-q-c-50-50-6.jpg\'> NOW I can put any css or <span style=\'color :red;\'>html</span> in here';">English</button>  
<button onclick="document.getElementById('chgtext').innerHTML='Text changed into Another <span style=\'color :red;\'>language</span>';">Other language</button>
<div id="chgtext">This is the default text. I can't put any css or html in here</div>
<p>
<style>
#eng_lang {
display: block;
}
#nl_lang {
display: none;
}
</style>
<button onclick=" document.getElementById('eng_lang').style.display='block'; document.getElementById('nl_lang').style.display='none'">English</button>   <button onclick="document.getElementById('eng_lang').style.display='none';document.getElementById('nl_lang').style.display='block'">Nederlands</button></p>
<div id="eng_lang">
<h2>Here is some text
<span style="color: green;">english</span>
</h2>
<img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRo2yKPonCY-BZrk9s69oH_-gal_yxDRgHxdyXhqP79D0YESVuB" width="120px" height="120px">
Now you can place here any text, tags and images.
</div>
<div id="nl_lang">
<h2>Here is another text
<span style="color: blue;">Netherlands</span>
</h2>
<img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQcE1c0chXugmq_V5qwp51ffAuP7ecGMsWmshnntwAXVGUgVptH" width="100px" height="100px">
Put here whatever you want.
<p>This is paragraph</p>
</div>

Categories