How do I check if a letter is bold? - javascript

I'm trying to change all bold characters to italic ones and vica versa. I figured out I need to iterate through the entire document.
So far I defined the two styles and a part of the function, not sure if the styles are needed.
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
<script>
function swap() {
if (fontWeight == 'bold') {
fontWeight == 'normal';
fontStyle == 'italic';
}
elseif (fontStyle == 'italic') {
fontStyle == 'normal';
fontWeight == 'bold';
}
</script>

Well, you could do this with querySelectorAll, considering only swapping .bold and .italic depending on their current class:
function swapCollection( collection, from, to ) {
if ( !collection ) {
return;
}
for( let i = 0; i < collection.length; ++i ) {
const elm = collection[ i ];
elm.classList.remove( from );
elm.classList.add( to );
}
}
function swap() {
const allBold = document.querySelectorAll( '.bold' );
const allItalic = document.querySelectorAll( '.italic' );
swapCollection( allBold, 'bold', 'italic' );
swapCollection( allItalic, 'italic', 'bold' );
}
document.getElementById( 'swap' ).addEventListener( 'click', swap );
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
<div>
<span class="bold">Hello</span> <span class="italic">world!</span>
</div>
<button id="swap">swap</button>

You can also use getElementsByClassName to choose class and change style then:
function swap() {
var mass=document.getElementsByClassName("bold");
for (i in mass){
mass[i].style.fontWeight="normal";
}
}

it's not useful to add a JS script for something that can be done once and for all.
so try to overwrite the default style of strong and em tags inyour CSS files by adding the following CSS code
strong, b{ font-weight: normal!important; font-style: italic!important; }
em, i{font-style: normal!important; font-weight: bold!important; }
then replace all properties in your CSS files
font-style: italic; by font-weight: bold;
and
font-weight: bold; by font-style: italic;
using your IDE

This is a generalize solution, using jQuery, not based only on class names.
I do the bolded texts red so you can see it easily.
$('div').each(function () {
if ($(this).css('font-weight') == 'bold') {
$(this).css('color', 'red'); // but you change to italic
return;
}
if ($(this).css('font-style') == 'italic') {
$(this).css('color', 'green'); // but you change to bold
return;
}
});
.one, .three {font-weight: bold;}
.five {font-style: italic;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one">aaa</div>
<div>ccc</div>
<div class="three">ddd</div>
<div>eee</div>
<div style="font-weight: bold;">lala</div>
<div style="font-style: italic;">tata</div>
<div>nana</div>
<div class="five">dada</div>
If you want to apply something to a text which is both bold and italic, remove the returns in the if blocks.

If it is simply a matter of toggling the classes, you could do it like this. Each time you click the button it will change the bold text to italic and vice versa.
const
trigger = document.getElementById('trigger');
function toggleClasses() {
const
// Get all the elements with the bold and/or italic class.
elements = document.querySelectorAll('.bold, .italic');
// Iterate over all the elements
elements.forEach(element => {
// For each element, toggle the bold and italic classes.
element.classList.toggle('bold');
element.classList.toggle('italic');
});
}
trigger.addEventListener('click', toggleClasses);
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
<p class="bold">initally bold</p>
<p class="bold">initally bold</p>
<p class="italic">initally italic</p>
<p class="bold">initally bold</p>
<p class="italic">initially italic</p>
<button id="trigger" type="button">toggle classes</button>

You may simply collect all items with .bold and .italic classes under a node list with document.querySelectorAll(".bold, .italic") and toggle their classLists.
var sps = document.querySelectorAll(".bold, .italic"),
mbt = document.getElementById("mbt");
mbt.addEventListener("click", _ => sps.forEach(function(sp){
sp.classList.toggle("bold");
sp.classList.toggle("italic");
}));
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
<p><span class="bold">Hello</span> <span class="italic">World</span></p>
<button id="mbt">Toggle</button>

Related

Changing a text color by javascript without changing its :hover color

I have this css :
.overlay-left-a {
color:red;
}
.overlay-left-a:hover {
color:black;
}
And this javascript :
let gr1 = document.getElementsByClassName("overlay-left-a");
for (let i = 0; i < gr1.length; i++) {
gr1[i].style.color = blue;
}
But I wish my javascript don't change the ':hover' color.
What is please the best way ?
In your case you can do it like this: Change a CSS variable without overriding the hover color. The main part is this CSS:
:root {
--color: red;
}
.overlay-left-a {
color: var(--color);
}
Then you can change the value of the color on :root like this:
document.documentElement.style.setProperty("--color", "blue");
// Or whatever −−−−^^^^^^
Live Example:
document.querySelector("input[type=button]").addEventListener("click", (e) => {
// Get the color
const color = document.getElementById("txt-color").value.trim();
// Apply it
document.documentElement.style.setProperty("--color", color);
});
:root {
--color: red;
}
.overlay-left-a {
color: var(--color);
}
.overlay-left-a:hover {
color: black;
}
test
test
test
test
<div>
<label>
Color name: <input type="text" id="txt-color" value="blue">
</label>
<input type="button" value="Set Color">
</div>
Use another class, not inline styles, that uses :not(:hover) to say not to apply it to hovered elements. (:not is the negation-pseudo class, which you can put a simple selector inside.)
.overlay-left-a.blue:not(:hover) {
color: blue;
}
document.querySelector("input[type=button]").addEventListener("click", (e) => {
e.currentTarget.disabled = true;
let gr1 = document.getElementsByClassName("overlay-left-a");
for (let i = 0; i < gr1.length; i++) {
gr1[i].classList.add("blue");
}
});
.overlay-left-a {
color:red;
}
.overlay-left-a:hover {
color:black;
}
.overlay-left-a.blue:not(:hover) {
color: blue;
}
<div class="overlay-left-a">hover me</div>
<input type="button" value="Click To Change Color To Blue">
In a comment you've indicated that the color is provided dynamically, so the above won't work for your specific situation.
To do that, you can use a CSS variable as mmh4all shows. If you can't use a CSS variable for some reason (obsolete browsers or something), you can add a style element to your page:
document.querySelector("input[type=button]").addEventListener("click", (e) => {
// Get the color
const color = document.getElementById("txt-color").value.trim();
// Create or update a style element applying that color
// to `.overlay-left-a` elements
let style = document.getElementById("overlay-left-a-color");
if (!style) {
style = document.createElement("style");
style.id = "overlay-left-a-color";
document.querySelector("head").appendChild(style);
}
style.textContent = `.overlay-left-a:not(:hover) { color: ${color}; }`;
});
.overlay-left-a {
color:red;
}
.overlay-left-a:hover {
color:black;
}
<div class="overlay-left-a">hover me</div>
<label>
Color name: <input type="text" id="txt-color" value="blue">
</label>
<input type="button" value="Set Color">

How to change an id of a span tag using query?

I have a program where everything works except one line. The code is to apply the class "footerStyle" to the span id named "footer1". When working correctly the line in footer1 should increase in size and change font family's.
Code must use querySelector or querySelectorAll
Full code, but code in question is labeled.
LOCATION - THIRD LINE FROM END
<style>
/*class names always begin with a . */
.ImportantStuff {
color: red;
font-family: Britannic;
font-size: xx-large;
text-align: center;
}
.SortOfImportantStuff {
color: green;
font-family: Calibri;
font-size: x-large;
text-align: center;
}
/*ids always begin with a # */
/*it will look for all elements with id of ChangeButton*/
#ChangeButton {
background-color:orange;
}
/*for the style below: since there is no # or . - it will look for an HTML element*/
/*so all div tags will follow this style*/
div {
color: blue;
font-family: cursive;
font-size: medium;
}
.footerStyle{
font-family:'Lucida Sans';
font-size: x-large;
}
</style>
</head>
<body>
<!--all the attributes of an object appear in red:-->
<input id="ChangeButton" type="button" value="Change the look of this page." onclick="ChangeThis()" />
<h1 class="ImportantStuff">Here we go - let's have some fun.</h1>
<p>In case you'd rather be on some much funner web sites:</p>
<br />
<!--target = "_blank" makes the page open in a new window or tab-->
Cedar Point
<br />
Face Book
<br />
YouTube
<br />
<div>
<b>Places I'd like to visit:</b>
<div>
Alaska
<img src="Images/Alaska.jpg" />
</div>
<div>
Australia
<img src="Images/Australia.jpg" />
</div>
<div>
Maine
<img src="Images/Maine.jpg" />
</div>
</div>
<span id="footer1">Maybe someday I'll get to these places.</span>
<br />
<span id="footer2">Until then, I'll just save my money.</span>
<script>
function ChangeThis() {
var allas = document.querySelectorAll("a");
for (x = 0; x < allas.length; x++) {
allas[x].setAttribute("class", "SortOfImportantStuff");
}
document.querySelector("p").style.color = "red";
document.querySelector("p").style.backgroundColor = "green";
var allimgs = document.querySelectorAll("img");
for (x = 0; x < allimgs.length; x++) {
allimgs[x].style.width = 250 + 'px';
allimgs[x].style.height = 150 + 'px';
}
var InnerDivs = document.querySelectorAll("div div");
for (x = 0; x < InnerDivs.length; x++) {
InnerDivs[x].style.color = "red";
}
//CODE IN QUESTION
document.querySelector("#footer1", ".footerStyle");
//
document.querySelector('#footer2').textContent = 'Happy Halloween';
}
</script>
Answer:
document.querySelector('#footer1').setAttribute("class", "footerStyle");

CSS Not Applied to Node Added by JS appendChild

My html:
<div id=Info>
<p>Id: <span>001</span></p>
</div>
My CSS:
#Info p {
font-weight: bold;
}
#Info span {
font-weight: normal;
}
My JS code:
var pElement = document.createElement('p');
var spanElement = document.createElement("span");
var elementValue1 = document.createTextNode("Id: ");
var elementValue2 = document.createTextNode("003");
spanElement.appendChild(elementValue1);
pElement.appendChild(elementValue2);
pElement.appendChild(spanElement);
document.querySelector('#Info').appendChild(pElement);
CSS style applied correctly to the line:<p>Id: <span>001</span></p> from html file. But somehow, CSS style is not applied to the node added by appendChild from JS file. I couldn't figure out why.
I'm new to html/CSS/JS, any help would be appreciated!
Thanks!
It looks like the div id is not match between your html and the css.
In the html, the id=Info should be id="bookInfo"
Is seems to be qworking perfectly fine, but there are multiple issues in shared code.
CSS is referring to #bookInfo as opposed to #Info
You are appending elementValue1 to spanElement as opposed to elementValue2.
Let's look at fixed code:
var pElement = document.createElement('p');
var spanElement = document.createElement("span");
var elementValue1 = document.createTextNode("Id: ");
var elementValue2 = document.createTextNode("003");
spanElement.appendChild(elementValue2);
pElement.appendChild(elementValue1);
pElement.appendChild(spanElement);
document.querySelector('#Info').appendChild(pElement);
#Info p {
font-weight: bold;
}
#Info span {
font-weight: normal;
}
<div id=Info>
<p>Id: <span>001</span></p>
</div>
not a good way to do it but here is your code:
https://jsfiddle.net/r6j31zhL/
<html>
<body>
<div id="Info">
<p>Id: <span>001</span></p>
</div>
</body>
</html>
<style>
#Info p {
font-weight: bold;
}
#Info span {
font-weight: normal;
}
</style>
<script>
var pElement = document.createElement('p');
var spanElement = document.createElement("span");
var elementValue1 = document.createTextNode("Id: ");
var elementValue2 = document.createTextNode("003");
spanElement.appendChild(elementValue2);
pElement.appendChild(elementValue1);
pElement.appendChild(spanElement);
document.querySelector('#Info span').appendChild(pElement);
</script>

How to add closeable text tags to Textarea Kendo | jQuery

I need to use Text area like this image.
I should able to click Text A, Text B, Text C, Text D buttons and, once I click any of this button it should add to the Text area and also able remove added text field from the Text area. Can I do it using jQuery UI , jQuery or JavaScript .Kendo UI is also okay. but I'm unable to found my requirement support Kendo component to do this.
I researched and found this http://skfox.com/jqExamples/insertAtCaret.html , but it's not support added text fields removable function,
As was mentioned in my previous comments on your previous post, this cannot be done with a <textarea> element. These elements can only contain text, they cannot contain other elements like <button> or <span> which would be required to make a remove button.
The following is a very lightweight example and it has many pitfalls. It does give you some ideas of how you might look at proceeding.
$(function() {
function calcWordWidth(str, fontfamily, fontsize) {
var word = $("<span>").css({
display: "none",
"font-family": fontfamily,
"font-size": fontsize
}).html(str).appendTo("body");
var width = word.width();
word.remove();
return width;
}
function addCloseButton(pos, st, en, trg) {
var btn = $("<span>", {
class: "closeBtn"
}).html("x");
btn.css({
position: "absolute",
left: pos + "px",
top: "1px"
});
trg.parent().append(btn);
btn.click(function() {
removeText(st, en, trg);
$(this).remove();
});
}
function addText(str, trg) {
var cur = trg.val();
var start = cur.length;
if (start) {
trg.val(cur + " " + str);
} else {
trg.val(str);
}
cur = trg.val();
var end = cur.length;
var width = calcWordWidth(cur, trg.css("font-family"), trg.css("font-size"));
console.log(width);
addCloseButton(width, start, end, $("#txtMessage"));
}
function removeText(start, end, trg) {
var cur = trg.val();
var upd = cur.slice(0, start) + " " + cur.slice(end);
trg.val(upd);
}
$("button").click(function() {
addText($(this).val(), $("#txtMessage"));
});
});
.closeBtn {
font-family: Arial;
font-size: 12px;
cursor: pointer;
padding: 1px;
background: #ccc;
border-radius: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="maincontainer">
<div id="navtoplistline"> </div>
<div id="contentwrapper">
<div><button id="btn-1" value="Hello World!">Hello World!</button></div>
<div id="maincolumn">
<div class="text" style="position: relative;">
<textarea name="txtMessage" id="txtMessage" class="txtDropTarget ui-droppable" cols="80" rows="15"></textarea>
</div>
</div>
</div>
</div>
You can also look at using a <div> element with the contenteditable attribute enabled. Again, pretty complex and would not advise it.
As I suggested, you may be better off using something like TinyMCE. TinyMCE is a JavaScript based Rich Text editor that is highly customizable.
Example: https://jsfiddle.net/Twisty/fngjcse3/
JavaScript
tinymce.init({
selector: 'textarea',
menubar: false,
statusbar: false,
plugins: "code",
toolbar: 'helloWorld allBase code',
setup: function(editor) {
var makeSpan = function(str) {
return '<span class="word"> ' + str + ' <em>x</em><span> ';
}
editor.ui.registry.addButton('helloWorld', {
text: 'Hello World!',
onAction: function(_) {
editor.insertContent(makeSpan("Hello World!"));
}
});
editor.ui.registry.addButton('allBase', {
text: 'All your Base',
onAction: function(_) {
editor.insertContent(makeSpan("All your base"));
}
});
},
content_style: 'span.word em { font-style: normal; font-size: 12px; background: #ccc; cursor: pointer; padding: 1px; border-radius: 3px; }',
init_instance_callback: function(editor) {
editor.on('click', function(e) {
if (e.target.nodeName == "EM") {
console.log("Remove Word.");
e.target.parentElement.remove();
}
});
}
});
This initializes TinyMCE with custom buttons. These buttons add the HTML that would be needed. You can also initialize it with custom callbacks, this can handle the close or remove options you are looking for.

Change a selected id's class when on click JavaScript

I'm looking for a method of changing the class of a selected id. I aim to do this with java but I can't seem to work out how. So in my example I have 4 "p" tags each with a different id and all with the class "na" now what I want to do is when one of the "p" tags is click it swaps the class to "under" and resulting in the tag being underlined. Can anyone point me in the right direction here to simplify it?
EDIT
Sorry guys, I forgot to add the JavaScript.
function class1() {
document.getElementById("p1").className = "under";
document.getElementById("p2").className = "na";
document.getElementById("p3").className = "na";
document.getElementById("p4").className = "na";
}
function class2() {
document.getElementById("p1").className = "na";
document.getElementById("p2").className = "under";
document.getElementById("p3").className = "na";
document.getElementById("p4").className = "na";
}
function class3() {
document.getElementById("p1").className = "na";
document.getElementById("p2").className = "na";
document.getElementById("p3").className = "under";
document.getElementById("p4").className = "na";
}
function class4() {
document.getElementById("p1").className = "na";
document.getElementById("p2").className = "na";
document.getElementById("p3").className = "na";
document.getElementById("p4").className = "under";
}
.under {
font-size: 16px;
font-weight: bold;
text-decoration: underline;
}
.na {
font-size: 16px;
font-weight: bold;
}
<p id="p1" class="na" onclick="class1()">Para1</p>
<p id="p2" class="na" onclick="class2()">Para2</p>
<p id="p3" class="na" onclick="class3()">Para3</p>
<p id="p4" class="na" onclick="class4()">Para4</p>
It looks like you over-complicated the task.
Using jQuery, this is super simple to achieve in only one "two lines" function.
$(".na").on("click", function(){
// Remove the class under from all p element.
$(".na").removeClass("under");
// Add the class under to the one clicked.
$(this).addClass("under");
});
.under {
text-decoration: underline;
}
.na {
font-size: 16px;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="p1" class="na">Para1</p>
<p id="p2" class="na">Para2</p>
<p id="p3" class="na">Para3</p>
<p id="p4" class="na">Para4</p>

Categories

Resources