How to toggle a button with JS - javascript

I have a button and it should increase the font size when clicked and if it's clicked again it should decrease the font. Also the value of the button should change to Increase Font / Decrease Font. So, basically I want to make the button toggle from increasing the font to 16px then decreasing to 14px if clicked again.
EDIT: I made it work but it doesn't keep repeating. Only works twice and that's it
HTML
<p id="increase">Lorem Ipsum.</p>
<input onclick="font()" style="background-color:#72cf26" type="submit" value="Increase Font" id = "fontbutton"/>
JS
function font(){
var fontsize = document.getElementById('increase');
var fontbutton = document.getElementById('fontbutton');
if (fontbutton.value == "Increase Font"){
fontsize.classList.add("font16");
document.getElementById('fontbutton').value = "Decrease Font";
}else if (fontbutton.value == "Decrease Font"){
fontsize.classList.add("font14");
document.getElementById('fontbutton').value = "Increase Font";
}
}
CS
.font16{
font-size:16px;
}
.font14{
font-size: 14px;
}

You should use fontbutton.value instead of fontbutton.getElementById.value and remove the previous class using fontsize.classList.remove to add the new one using fontsize.classList.add:
function font(){
var fontsize = document.getElementById('increase');
var fontbutton = document.getElementById('fontbutton');
if (fontbutton.value == "Increase Font"){
fontsize.classList.remove("font14");
fontsize.classList.add("font16");
fontbutton.value = "Decrease Font";
}else if (fontbutton.value == "Decrease Font"){
fontsize.classList.remove("font16");
fontsize.classList.add("font14");
fontbutton.value = "Increase Font";
}
}
.font16{
font-size:16px;
}
.font14{
font-size: 14px;
}
<p id="increase" class="font14">Lorem Ipsum.</p>
<input onclick="font()" style="background-color:#72cf26" type="submit" value="Increase Font" id = "fontbutton"/>

The above requirement can be implemented using
element.classlist.add and element.classlist.remove functions.
Here is a copy of the working code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.font16{
font-size:16px;
background-color:#72cf26;
}
.font14{
font-size: 14px;
background-color:#72cf26;
}
</style>
</head>
<body>
<p id="increase">Lorem Ipsum.</p>
<button id="fontbutton" class="font14" onclick="toggleFont()">
Increase Font
</button>
<script>
function toggleFont() {
var element = document.getElementById("fontbutton")
var buttonText = element.innerHTML
element.classList.remove("font14")
element.classList.remove("font16")
if(buttonText.indexOf("Increase") >= 0) {
element.classList.add("font16")
element.innerHTML = "Decrease font"
} else {
element.classList.add("font14")
element.innerHTML = "Increase font"
}
}
</script>
</body>
</html>
Output:
More information:
https://www.w3schools.com/howto/howto_js_toggle_class.asp

$(document).ready(function(){
var flag = true;
$('.btn').click(function(){
$(this).find('span').toggleClass('hidden');
if(flag) {
$('#increase').addClass('font16');
$('#increase').removeClass('font14');
flag = !flag;
}else {
$('#increase').removeClass('font16');
$('#increase').addClass('font14');
flag = !flag;
}
});
});
.font16{
font-size:16px;
}
.font14{
font-size: 14px;
}
.hidden {
display: none;
}
p{ font-size: 10px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="increase">Lorem Ipsum.</p>
<button class="btn">
<span>Increse Font</span>
<span class="hidden">Decrese Font</span>
</button>

Your approach is complicated, JS directly offers a toggle method to add / delete a class and which returns a boolean value.
The only difficulty is that you should not forget to add !important to upgrade the size.
const paragraphInc = document.getElementById('increase')
, buttonSize = document.getElementById('fontbutton')
;
buttonSize.onclick = () =>
{
buttonSize.textContent = (paragraphInc.classList.toggle('Size16'))
? 'Decrease Font'
: 'Increase Font'
}
#fontbutton {
background-color:#72cf26;
padding: 7px 12px;
}
#increase {
font-size: 14px;
}
.Size16 {
font-size: 16px !important;
}
<p id="increase">Lorem Ipsum.</p>
<button id="fontbutton">Increase Font</button>

Related

How to allow user to change font size

I am making a google docs like app, and I want the user to be able to select the text, and then change the size to whatever they want. I tried to use variables but it didn't work so I am not sure what to do. Is there any way to allow the user to change the font size and if so how?
Here is the code for the app:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Editor</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<button class="bold" onclick="document.execCommand('bold',false,null);">
𝗕
</button>
<button class="italic" onclick="document.execCommand('italic',false,null);">
𝘐
</button>
<button
class="underline"
onclick="document.execCommand('underline',false,null);"
>
U̲
</button>
<input
type="color"
class="color-picker"
id="colorPicker"
oninput="changeColorText(this.value);"
/>
<label>Select color</label>
<button id="highlight"><mark>Highlight</mark></button>
<fieldset class="userInput" contenteditable="true"></fieldset>
<script>
var boldBtn = document.querySelector(".bold");
var italicBtn = document.querySelector(".italic");
var underlineBtn = document.querySelector(".underline");
var colorPicker = document.querySelector(".color-picker");
var highlightBtn = document.querySelector("#highlight");
boldBtn.addEventListener("click", function () {
boldBtn.classList.toggle("inUse");
});
italicBtn.addEventListener("click", function () {
italicBtn.classList.toggle("inUse");
});
underlineBtn.addEventListener("click", function () {
underlineBtn.classList.toggle("inUse");
});
highlightBtn.addEventListener("click", function () {
highlightBtn.classList.toggle("inUse");
});
const changeColorText = (color) => {
document.execCommand("styleWithCSS", false, true);
document.execCommand("foreColor", false, color);
};
document
.getElementById("highlight")
.addEventListener("click", function () {
var range = window.getSelection().getRangeAt(0),
span = document.createElement("span");
span.className = "highlight";
span.appendChild(range.extractContents());
range.insertNode(span);
});
</script>
</body>
</html>
I think this is the output you want. Also, don't use document.execCommand, it has been deprecated
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Editor</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<button class="bold" onclick="document.execCommand('bold',false,null);">
𝗕
</button>
<button class="italic" onclick="document.execCommand('italic',false,null);">
𝘐
</button>
<button
class="underline"
onclick="document.execCommand('underline',false,null);"
>
U̲
</button>
<input
type="color"
class="color-picker"
id="colorPicker"
oninput="changeColorText(this.value);"
/>
<label>Select color</label>
<button id="highlight"><mark>Highlight</mark></button>
<input
type="number"
class="font-size"
id="fontSize"
/>
<label>Select Font Size</label>
<fieldset class="userInput" contenteditable="true"></fieldset>
<script>
var boldBtn = document.querySelector(".bold");
var italicBtn = document.querySelector(".italic");
var underlineBtn = document.querySelector(".underline");
var colorPicker = document.querySelector(".color-picker");
var fontSize = document.querySelector("#fontSize");
var highlightBtn = document.querySelector("#highlight");
var userInput = document.querySelector('.userInput');
boldBtn.addEventListener("click", function () {
boldBtn.classList.toggle("inUse");
});
italicBtn.addEventListener("click", function () {
italicBtn.classList.toggle("inUse");
});
underlineBtn.addEventListener("click", function () {
underlineBtn.classList.toggle("inUse");
});
highlightBtn.addEventListener("click", function () {
highlightBtn.classList.toggle("inUse");
});
const changeColorText = (color) => {
document.execCommand("styleWithCSS", false, true);
document.execCommand("foreColor", false, color);
};
fontSize.addEventListener('input', updateValue);
function updateValue(e) {
userInput.style.fontSize = `${e.target.value}px`;
}
document
.getElementById("highlight")
.addEventListener("click", function () {
var range = window.getSelection().getRangeAt(0),
span = document.createElement("span");
span.className = "highlight";
span.appendChild(range.extractContents());
range.insertNode(span);
});
</script>
</body>
</html>
Add this to your HTML:
<button class="font-smaller">-</button>
<button class="font-bigger">+</button>
Add this to your JS:
const fontSmaller = document.querySelector(".font-smaller");
const fontBigger = document.querySelector(".font-bigger");
let fontSize = 15.5; // play with this number if needed
fontSmaller.addEventListener("click", () => {
document.querySelector(".userInput").style.fontSize = `${fontSize--}px`;
});
fontBigger.addEventListener("click", () => {
document.querySelector(".userInput").style.fontSize = `${fontSize++}px`;
});
Change as needed. This will change the size of the whole text.
You can implement it like this.
// Increase/descrease font size
$('#increasetext').click(function() {
curSize = parseInt($('#content').css('font-size')) + 2;
if (curSize <= 32)
$('#content').css('font-size', curSize);
});
$('#resettext').click(function() {
if (curSize != 18)
$('#content').css('font-size', 18);
});
$('#decreasetext').click(function() {
curSize = parseInt($('#content').css('font-size')) - 2;
if (curSize >= 14)
$('#content').css('font-size', curSize);
});
header {
text-align: center;
}
/* text-controls */
button {
vertical-align: bottom;
margin: 0 0.3125em;
padding: 0 0.3125em;
border: 1px solid #000;
background-color: #fff;
font-weight: bold;
}
button#increasetext {
font-size: 1.50em;
}
button#resettext {
font-size: 1.25em;
}
button#decreasetext {
font-size: 1.125em;
}
.textcontrols {
padding: 0.625em 0;
background: #ccc;
}
/* content */
#content {
margin: 3em 0;
text-align: left;
}
/* demo container */
#container {
width: 90%;
margin: 0 auto;
padding: 2%;
}
#description {
margin-bottom: 1.25em;
text-align: left;
}
#media all and (min-width: 700px) {
#container {
width: 700px;
}
button {
margin: 0 0.625em;
padding: 0 0.625em;
}
}
<div id="container">
<header>
<h1 id="title">
Allow Users to Change Font Size
</h1>
<p>Click the buttons to see it in action</p>
<div class="textcontrols">
<button role="button" id="decreasetext" <span>smaller</span>
</button>
<button role="button" id="resettext">
<span>normal</span>
</button>
<button role="button" id="increasetext">
<span>bigger</span>
</button>
</div>
<!--/.textcontrols-->
</header>
<main id="content" role="main">
<div id="description">
<h2>Allow users to resize text on the page via button controls.</h2>
<p>In this instance, users can decrease text, increase text, or reset it back to normal.</p>
<h2>Set default text size with CSS</h2>
<p>The default text size must be set using an internal stylesheet in the header of your page. In this case: <code>font-size: 1.125em</code> (aka, 18px).</p>
<h2>Set the controls with JavaScript</h2>
<p>Then we set the resize controls with JavaScript. In this example, we're resizing all text within the div with an id of "content".</p>
<p>The controls check the current text size, and then changes it (or not) accordingly.</p>
</div>
<!--/#description-->
</main>
<!--/#content-->
</div>
<!--/#container-->

how to save toogle class with localstorage. so can someone check what's wrong with this code

if( localStorage.getItem("color") == "black" ) {
{
var element = document.getElementById("body");
element.classList.toggle("bdark");
}
{
var element = document.getElementById("theader");
element.classList.toggle("hdark");
}
{
var element = document.getElementById("sh");
element.classList.toggle("shh");
}
}
function myFunction() {
{
var element = document.getElementById("body");
element.classList.toggle("bdark");
}
{
var element = document.getElementById("theader");
element.classList.toggle("hdark");
}
{
var element = document.getElementById("sh");
element.classList.toggle("shh");
}
var hs = document.getElementById("hs");
var color;
if(localStorage.getItem("color") == "black") {
color = "black";
localStorage.setItem("color",color)
}
.bdark {
background-color: #333;
color: white;
}
.hdark {
background-color: black;
color: white;
}
.shh {
display: none;
}
.hs {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body id="body" class="light">
<p id="theader">Click the "Try it" button to toggle between adding and removing the "mystyle" class name of the DIV element:</p>
<button id="button" onclick="myFunction()">Try it</button>
<div id="aaas">
<div id="sh" class="sh">☾</div>
<div id="hs" class="hs">☀</div>
</div>
</body>
</html>
i want this code to onclick toggle class and when i refresh the page those toggled class remain same as they were before reloading the page with localstorage. so can someone check what's wrong with this code. help me with something similar/alternative to this one. thanks for reading this.
Details:-
i want this code to work as (onclick class change + saved with cokies/localstorage/or anything) so whenever i refresh or reopen the page it would be same class as it was when i left. or some alternative code that works same.
I fixed your code
if( localStorage.getItem("color") == "black" ) {
{
let element = document.getElementsByTagName("body");
element.classList.toggle("bdark");
}
{
let element = document.getElementById("theader");
element.classList.toggle("hdark");
}
{
let element = document.getElementById("sh");
element.classList.toggle("shh");
}
}
function myFunction() {
{
let element = document.getElementsByTagName("body");
element.classList="bdark";
}
{
let element = document.getElementById("theader");
element.classList="hdark";
}
{
let element = document.getElementById("sh");
element.classList="shh";
}
{
let hs = document.getElementById("hs");
}
let color;
if(localStorage.getItem("color") != "black") {
color = "black";
localStorage.setItem("color", color)
}
}
.bdark {
background-color: #333;
color: white;
}
.hdark {
background-color: black;
color: white;
}
.shh {
display: none;
}
.hs {
display: none;
}
<p id="theader">Click the "Try it" button to toggle between adding and removing the "mystyle" class name of the DIV element:</p>
<button id="button" onclick="myFunction()">Try it</button>
<div id="aaas">
<div id="sh" class="sh">☾</div>
<div id="hs" class="hs">☀</div>
</div>

how to save toogle class with localstorage/cookies. so can someone check what's wrong with this code

if( localStorage.getItem("color") == "black" ) {
var classlist = document.getElementById("body").classList;
clasList.add("bdark");
classList = document.getElementById("theader").classList;
classList.add("hdark");
classList = document.getElementById("sh").classList;
classList.add("shh");
var hs = document.getElementById("hs").classList;
document.getElementById("hs").style.display = "block";
}
function myFunction() {
var classlist = document.getElementById("body").classList;
clasList.toggle("bdark");
classList = document.getElementById("theader").classList;
classList.toggle("hdark");
classList = document.getElementById("sh").classList;
classList.toggle("shh");
var hs = document.getElementById("hs");
if (hs.style.display === "block") {
hs.style.display = "none";
} else {
hs.style.display = "block";
}
var color;
if(localStorage.getItem("color") == "black") {
color = "black";
localStorage.setItem("color",color)
}
.bdark {
background-color: #333;
color: white;
}
.hdark {
background-color: black;
color: white;
}
.shh {
display: none;
}
.hs {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body id="body" class="light">
<p id="theader">Click the "Try it" button to toggle between adding and removing the "mystyle" class name of the DIV element:</p>
<button id="button" onclick="myFunction()">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>
<div id="aaas">
<div id="sh" class="sh">☾</div>
<div id="hs" class="hs">☀</div>
</div>
</body>
</html>
i want this code to onclick toggle class and when i refresh the page those toggled class remain same as they were before reloading the page with localstorage. so can someone check what's wrong with this code. help me with something similar/alternative to this one. thanks for reading this.
Details:-
i want this code to work as (onclick class change + saved with cokies/localstorage/or anything) so whenever i refresh or reopen the page it would be same class as it was when i left. or some alternative code that works same.
There are variable spelling mistakes in your code (declared as classlist and used as clasList)
missed closed brackets for the if condition in myFunction.
updated logic for storing color value.
I updated the above changes in your code.
I have added code here also you can check output in it.
Updated code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body id="body" class="light">
<p id="theader">Click the "Try it" button to toggle between adding and removing the "mystyle" class name of the DIV element:</p>
<button id="button" onclick="myFunction()">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>
<div id="aaas">
<div id="sh" class="sh">☾</div>
<div id="hs" class="hs">☀</div>
</div>
</body>
</html>
.bdark {
background-color: #333;
color: white;
}
.hdark {
background-color: black;
color: white;
}
.shh {
display: none;
}
.hs {
display: none;
}
if (localStorage.getItem("color") === "black") {
var classlist = document.getElementById("body").classList;
classlist.add("bdark");
classlist = document.getElementById("theader").classList;
classlist.add("hdark");
classlist = document.getElementById("sh").classList;
classlist.add("shh");
document.getElementById("hs").style.display = "block";
}
function myFunction() {
var classlist = document.getElementById("body").classList;
classlist.toggle("bdark");
classlist = document.getElementById("theader").classList;
classlist.toggle("hdark");
classlist = document.getElementById("sh").classList;
classlist.toggle("shh");
var hs = document.getElementById("hs");
if (hs.style.display === "block") {
hs.style.display = "none";
} else {
hs.style.display = "block";
}
if (localStorage.getItem("color") === "black") {
localStorage.setItem("color", "white");
} else {
localStorage.setItem("color", "black");
}
}

Button Clicked change Colour

So little bit stuck here, I have several buttons that I want to do separate actions. For example of someone clicks the colour green it changes the paragraph text colour to green, I accomplished the first one but I can't seem to work others, what's the correct way to do it?
//JS:
function myFunction() {
var p = document.getElementById("paragraph"); // get the paragraph
document.getElementById("paragraph").style.color = "green";
var p = document.getElementById("paragraph"); // get the paragraph
document.getElementById("Bluecolour").style.color = "blue";
}
<!doctype html>
<html lang="en">
<head>
<title> Change Paratext </title>
<meta charset="utf-8">
<script src="task2.js"></script>
<style>
#paragraph {
padding: 10px;
margin-bottom: 10px;
background-color: silver;
border: 1px dashed black;
width: 90%; /* you can adjust this on Firefox if needed */
height: 200px;
overflow: hidden;
margin-top: 10px;
}
</style>
</head>
<body>
<h1> Ali Rizwan </h1>
<p id="paragraph"> Box changes text based on what colour is clicked <br>
<!-- add your buttons here. All buttons should be in one paragraph -->
</p>
<p id="buttons">
<button type="button" onclick="myFunction()" id="GreenColour">Green</button><!-- Changes text to Green -->
<button type="button" onclick="myFunction()" id="Bluecolour">Blue</button><!-- Changes text to Blue -->
<button type="button" onclick="myFunction()" id="Mono">Mono</button> <!-- Changes text to Mono -->
<button type="button" onclick="myFunction()" id="Sans Serif">Sans Serif</button> <!-- Changes text to Sans Serif -->
<button type="button" onclick="myFunction()" id="Serif">Serif</button> <!-- Changes text to Serif -->
<button type="button" onclick="myFunction()" id="SizeAdd">Size++</button> <!-- This button increases size by 1 every time its clicked -->
<button type="button"onclick="myFunction()" id="SizeMinus">Size--</button> <!-- This button decreases size by 1 every time its clicked -->
</p>
</div>
</body>
</html>
Your myFunction() doesn't know what it need to do when it has been called.
Try this entry level code, simply declare few function to change the text color:
function blue() {
var p = document.getElementById("paragraph"); // get the paragraph
p.style.color= 'blue'
}
function green() {
var p = document.getElementById("paragraph"); // get the paragraph
p.style.color= 'green'
}
function mono(){
var p = document.getElementById("paragraph"); // get the paragraph
p.style.fontFamily = "monospace"
}
<!doctype html>
<html lang="en">
<head>
<title> Change Paratext </title>
<meta charset="utf-8">
<script src="task2.js"></script>
<style>
#paragraph {
padding: 10px;
margin-bottom: 10px;
background-color: silver;
border: 1px dashed black;
width: 90%; /* you can adjust this on Firefox if needed */
height: 100px;
overflow: hidden;
margin-top: 10px;
}
</style>
</head>
<body>
<h1> Ali Rizwan </h1>
<p id="paragraph"> Box changes text based on what colour is clicked <br>
<!-- add your buttons here. All buttons should be in one paragraph -->
</p>
<p id="buttons">
<button type="button" onclick="green()">Green</button><!-- Changes text to Green -->
<button type="button" onclick="blue()">Blue</button><!-- Changes text to Blue -->
<button type="button" onclick="mono()">Mono</button><!-- Changes text to monospace-->
</p>
</div>
</body>
</html>
There are different ways to do that,
name distinct function name for distinct button id and set the background according to that
call the same function but this time inside the function pass a parameter of button ID
button type="button" onclick="myFunction(this.id)" id="GreenColour">Green
and the function is:
function myFunction(id) {
if(id=="GreenColour")
document.getElementById("paragraph").style.color="green"; // get the paragraph
//document.getElementById("paragraph").style.color = "green";
else if(id=="BlueColour")
document.getElementById("paragraph").style.color=blue; // get the paragraph
//document.getElementById("Bluecolour").style.color = "blue";
}
You could separate the logic into different functions and pass values as arguments to them:
const paragraph = document.getElementById("paragraph");
let fontSize = 1;
function setStyle(style, value) {
paragraph.style[style] = value;
}
function incrementSize(value) {
fontSize += value
paragraph.style.fontSize = `${fontSize}em` ;
}
<!doctype html>
<html lang="en">
<head>
<title> Change Paratext </title>
<meta charset="utf-8">
<script src="task2.js"></script>
<style>
#paragraph {
padding: 10px;
margin-bottom: 10px;
background-color: silver;
border: 1px dashed black;
width: 90%; /* you can adjust this on Firefox if needed */
height: 200px;
overflow: hidden;
margin-top: 10px;
}
</style>
</head>
<body>
<h1> Ali Rizwan </h1>
<p id="paragraph"> Box changes text based on what colour is clicked <br>
<!-- add your buttons here. All buttons should be in one paragraph -->
</p>
<p id="buttons">
<button type="button" onclick="setStyle('color', 'green')" id="GreenColour">Green</button><!-- Changes text to Green -->
<button type="button" onclick="setStyle('color', 'blue')" id="Bluecolour">Blue</button><!-- Changes text to Blue -->
<button type="button" onclick="setStyle('font-family', 'monospace')" id="Mono">Mono</button> <!-- Changes text to Mono -->
<button type="button" onclick="setStyle('font-family', 'sans-serif')" id="Sans Serif">Sans Serif</button> <!-- Changes text to Sans Serif -->
<button type="button" onclick="setStyle('font-family', 'serif')" id="Serif">Serif</button> <!-- Changes text to Serif -->
<button type="button" onclick="incrementSize(+0.1)" id="SizeAdd">Size++</button> <!-- This button increases size by 1 every time its clicked -->
<button type="button"onclick="incrementSize(-0.1)" id="SizeMinus">Size--</button> <!-- This button decreases size by 1 every time its clicked -->
</p>
</div>
</body>
</html>
Updated code using SWITCH case
//JS:
function myFunction(btnColor) {
var p = document.getElementById("paragraph"); // get the paragraph
switch(btnColor){
case 'green':
document.getElementById("paragraph").style.color = "green";
break;
case 'blue':
document.getElementById("paragraph").style.color = "blue";
break;
case 'mono':
document.getElementById("paragraph").style.color = "mono";
break;
case 'sansserif':
document.getElementById("paragraph").style.fontFamily = "Sans Serif";
break;
case 'serif':
document.getElementById("paragraph").style.fontFamily = "serif";
break;
case 'sizeadd':
var el = document.getElementById('paragraph');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style);
el.style.fontSize = (fontSize + 1) + 'px';
document.getElementById("paragraph").style.fontSize = "serif";
break;
case 'sizeminus':
var el = document.getElementById('paragraph');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style);
el.style.fontSize = (fontSize - 1) + 'px';
break;
}
}
#paragraph {
padding: 10px;
margin-bottom: 10px;
background-color: silver;
border: 1px dashed black;
width: 90%; /* you can adjust this on Firefox if needed */
height: 20px;
overflow: hidden;
margin-top: 10px;
}
<!doctype html>
<html lang="en">
<body>
<h1> Ali Rizwan </h1>
<p id="paragraph"> Box changes text based on what colour is clicked <br>
<!-- add your buttons here. All buttons should be in one paragraph -->
</p>
<p id="buttons">
<button type="button" onclick="myFunction('green')" id="GreenColour">Green</button><!-- Changes text to Green -->
<button type="button" onclick="myFunction('blue')" id="Bluecolour">Blue</button><!-- Changes text to Blue -->
<button type="button" onclick="myFunction('mono')" id="Mono">Mono</button> <!-- Changes text to Mono -->
<button type="button" onclick="myFunction('sansserif')" id="Sans Serif">Sans Serif</button> <!-- Changes text to Sans Serif -->
<button type="button" onclick="myFunction('serif')" id="Serif">Serif</button> <!-- Changes text to Serif -->
<button type="button" onclick="myFunction('sizeadd')" id="SizeAdd">Size++</button> <!-- This button increases size by 1 every time its clicked -->
<button type="button"onclick="myFunction('sizeminus')" id="SizeMinus">Size--</button> <!-- This button decreases size by 1 every time its clicked -->
</p>
</div>
</body>
</html>
the easiest way is to create function with parameter like myFunction(name, value)
var fontSize = 12;
function myFunction(name, value) {
var p = document.getElementById("paragraph");
if (value == 'SizeAdd') {
fontSize += 2;
value = fontSize + 'px';
}
if (value == 'SizeMinus') {
fontSize -= 2;
value = fontSize + 'px';
}
p.style[name] = value;
}
<p id="paragraph"> Box changes text based on what colour is clicked <br>
<!-- add your buttons here. All buttons should be in one paragraph -->
</p>
<p id="buttons">
<button type="button" onclick="myFunction('color', 'green')">Green</button>
<button type="button" onclick="myFunction('color', 'blue')">Blue</button>
<button type="button" onclick="myFunction('fontFamily', 'Mono')">Mono</button>
<button type="button" onclick="myFunction('fontFamily', 'Sans-Serif')">Sans Serif</button>
<button type="button" onclick="myFunction('fontFamily', 'Serif')">Serif</button>
<button type="button" onclick="myFunction('fontSize', 'SizeAdd')">Size++</button>
<button type="button" onclick="myFunction('fontSize', 'SizeMinus')">Size--</button>
</p>
First of all, for caching reasons, it's best to use external CSS and JavaScript. Just make sure you change your CSS and JavaScript file names every time you update the code when you go live. Also, it's a best practice to separate your HTML, CSS, and JavaScript.
Here is some code showing you how to change colors. It should be easy to see that you can just change the paraColor argument, following the design pattern below, to get the results you seek.
//<![CDATA[
/* js/external.js */
var doc, bod, htm, M, I, S, Q, paraColor; // for use on other loads
addEventListener('load', function(){
doc = document; bod = doc.body; htm = doc.documentElement;
M = function(tag){
return doc.createElement(tag);
}
I = function(id){
return doc.getElementById(id);
}
S = function(selector, within){
var w = within || doc;
return w.querySelector(selector);
}
Q = function(selector, within){
var w = within || doc;
return w.querySelectorAll(selector);
}
var para = I('paragraph'), pS = para.style;
paraColor = function(color){
pS.color = color;
}
I('greenColor').addEventListener('click', function(){
paraColor('green');
});
I('blueColor').addEventListener('click', function(){
paraColor('blue');
});
}); // load end
//]]>
/* css/external.css */
html,body{
padding:0; margin:0;
}
.main{
width:980px; margin:0 auto;
}
#paragraph{
height:100px; background-color:silver; padding:10px; border:1px dashed black;
margin:10px 0; overflow:hidden;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Paratext</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<h1>Ali Rizwan</h1>
<p id='paragraph'>Box changes text based on what color is clicked</p>
<p id='buttons'>
<input type='button' id='greenColor' value='Green' />
<input type='button' id='blueColor' value='Blue' />
</p>
</div>
</body>
</html>
Here is the full version of all buttons working, you can use switch case so you can use the same code for multiple buttons. I have used switch case
function myFunction(actionType,actionValue,currentButton) {
var increaseDecreaseFactor = 5;
switch (actionType) {
case 'color':
document.getElementById("paragraph").style.color = actionValue;
currentButton.style.color = actionValue;
break;
case 'increaseFont':
txt = document.getElementById("paragraph");
style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
currentSize = parseFloat(style);
txt.style.fontSize = (currentSize + increaseDecreaseFactor) + 'px';
break;
case 'decreaseFont':
txt = document.getElementById("paragraph");
style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
currentSize = parseFloat(style);
txt.style.fontSize = (currentSize - increaseDecreaseFactor) + 'px';
break;
case 'changeFont':
document.getElementById("paragraph").style.fontFamily = actionValue;
break;
default:
break;
}
}
#paragraph {
padding: 10px;
margin-bottom: 10px;
background-color: silver;
border: 1px dashed black;
width: 90%; /* you can adjust this on Firefox if needed */
height: 200px;
overflow: hidden;
margin-top: 10px;
}
<h1> Ali Rizwan </h1>
<p id="paragraph"> Box changes text based on what colour is clicked <br>
<!-- add your buttons here. All buttons should be in one paragraph -->
</p>
<p id="buttons">
<button type="button" onclick="myFunction('color','green',this)" id="GreenColour">Green</button><!-- Changes text to Green -->
<button type="button" onclick="myFunction('color','blue',this)" id="Bluecolour">Blue</button><!-- Changes text to Blue -->
<button type="button" onclick="myFunction('increaseFont','size++',this)" id="SizeAdd">Size++</button> <!-- This button increases size by 1 every time its clicked -->
<button type="button"onclick="myFunction('decreaseFont','size--',this)" id="SizeMinus">Size--</button> <!-- This button decreases size by 1 every time its clicked -->
<button type="button" onclick="myFunction('changeFont','monospace',this)" id="Mono">Mono</button> <!-- Changes text to Mono -->
<button type="button" onclick="myFunction('changeFont','Sans-Serif',this)" id="Sans Serif">Sans Serif</button> <!-- Changes text to Sans Serif -->
<button type="button" onclick="myFunction('changeFont','Serif',this)" id="Serif">Serif</button> <!-- Changes text to Serif -->
</p>
</div>
First add below link in your head section.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can do above things by this way :
$("button").click(function() {
var Id = $(this).attr('id');
if(Id == 'GreenColour'){
$("#"+Id).css('color','green');
}elseif(Id == 'Bluecolour'){
$("#"+Id).css('color','blue');
}elseif(...){
.....
}else(...){
.....
}
});
and so on. You can perform your different operation based on its ids in if else.
You can do it like this
<button type="button" onclick="myFunction()" id="GreenColour" c_name="green">Green</button><!-- Changes text to Green -->
<button type="button" onclick="myFunction()" id="Bluecolour" c_name="blue">Blue</button><!-- Changes text to Blue -->
function myFunction(evn) {
var color = event.currentTarget.getAttribute('c_name');
document.getElementById("paragraph").style.color = color;
event.currentTarget.style.color = color;
}
set the color name in div as attribute and read that attribute in calling function and use it.
So with your help and others that see this I learned this, essentially the button onclick name can be used in JS to change the text colour, define the button id, create a variable and then default JS to change the colour of paragraph.
HTML:
<!doctype html>
<html lang="en">
<head>
<title> Change Paratext </title>
<meta charset="utf-8">
<script src="task2.js"></script>
<style>
#paragraph {
padding: 10px;
margin-bottom: 10px;
background-color: silver;
border: 1px dashed black;
width: 90%; /* you can adjust this on Firefox if needed */
height: 100px;
overflow: hidden;
margin-top: 10px;
}
</style>
</head>
<body>
<h1> Ali Rizwan </h1>
<p id="paragraph"> Box changes text based on what colour is clicked <br>
<!-- add your buttons here. All buttons should be in one paragraph -->
</p>
<p id="buttons">
<button type="button" onclick="green()">Green</button><!-- Changes text to Green -->
<button type="button" onclick="blue()">Blue</button><!-- Changes text to Blue -->
<button type="button" onclick="mono()">Mono</button><!-- Changes text to monospace-->
<button type="button" onclick="sansserif()">Sans Serif</button><!-- Changes text to Sans Serif-->
<button type="button" onclick="serif()">Serif</button><!-- Changes text to Serif-->
</p>
</div>
</body>
</html>
JS:
function blue() {
var p = document.getElementById("paragraph"); // get the paragraph
p.style.color= 'blue'
}
function green() {
var p = document.getElementById("paragraph"); // get the paragraph
p.style.color= 'green'
}
function mono(){
var p = document.getElementById("paragraph"); // get the paragraph
p.style.fontFamily = 'monospace'
}
function sansserif(){
var p = document.getElementById("paragraph"); // get the paragraph
p.style.fontFamily = 'sans-serif'
}
function serif(){
var p = document.getElementById("paragraph"); // get the paragraph
p.style.fontFamily = 'serif'
}

Pass ID from one html element to another with JavaScript

my problem is pretty simple. I'm trying to switch 2 elements id by clicking either of them using only vanilla JavaScript.
It works on the first click to use the correct CSS for the new id, but afterward, it does not seem to recognize click events to the new id. Here is a short code example to illustrate this:
document.addEventListener("DOMContentLoaded", function(){
var blueSpin = document.getElementById("blue-spinner");
var orangeSpin = document.getElementById("orange-spinner");
blueSpin.addEventListener("click", function() {
document.getElementById("h1").innerHTML = "You've Clicked Blue";
blueSpin.setAttribute("id","orange-spinner");
orangeSpin.setAttribute("id", "blue-spinner")
});
orangeSpin.addEventListener("click", function() {
document.getElementById("h1").innerHTML = "You've Clicked Orange";
orangeSpin.setAttribute("id", "blue-spinner");
blueSpin.setAttribute("id", "orange-spinner");
});
});
h1, h2 {
font-weight: bold;
text-align: center;
font-size: 45px;
font-family: 'VT323', monospace;
margin: 15px;
}
#blue-spinner {
color: blue;
}
#orange-spinner {
color: goldenrod;
}
<script src="https://use.fontawesome.com/releases/v5.0.2/js/all.js"></script>
<html>
<body>
<h1 id="h1">Click Something:</h1>
<h2 id="blue-spinner"><i class="fa fa-cubes fa-spin" aria-hidden="true"></i></h2>
<h2 id="orange-spinner"><i class="fa fa-cubes fa-spin" aria-hidden="true"></i></h2>
</body>
</html>
My expectation is that upon clicking either spinner, the colors will switch, and the header will identify which one was clicked before the change. After that, you should be able to click either of the spinners with the same result.
Any help anyone can provide would be appreciated! Happy X-mas Eve Eve!
I would use class selectors in css instead of id. Something along these lines:
var btns = document.getElementsByClassName("btn");
for(var i = 0; i < btns.length; i++){
btns[i].addEventListener("click", function(e) {
var clss = e.target.getAttribute("class")
if(clss === undefined || cls === null){clss = "";}
if(cls.indexOf("blue-spinner") > -1){
var output = "You clicked a blue spinner";
e.target.setAttribute("class", "orange-spinner");
}else{
e.target.setAttribute("class", "blue-spinner");
var output = "You clicked an orange spinner";
}
var h = document.getElementById("h1");
h.innerHTML = output;
});
}
Since you change the id for the element you have to update your code after the change.
document.addEventListener("DOMContentLoaded", function() {
var blueSpin = document.getElementById("blue-spinner");
var orangeSpin = document.getElementById("orange-spinner");
var blueSpinClick = function() {
document.getElementById("h1").innerHTML = "You've Clicked Blue";
blueSpin.removeEventListener('click', blueSpinClick);
orangeSpin.removeEventListener('click', orangeSpinClick);
blueSpin.removeEventListener('click', blueSpinClick);
blueSpin.setAttribute("id","orange-spinner");
orangeSpin.setAttribute("id", "blue-spinner");
blueSpin = document.getElementById("blue-spinner");
orangeSpin = document.getElementById("orange-spinner");
blueSpin.addEventListener("click", blueSpinClick);
orangeSpin.addEventListener("click", orangeSpinClick);
}
document.getElementById("blue-spinner").addEventListener("click", blueSpinClick);
var orangeSpinClick = function() {
document.getElementById("h1").innerHTML = "You've Clicked Orange";
orangeSpin.removeEventListener('click', orangeSpinClick);
blueSpin.removeEventListener('click', blueSpinClick);
blueSpin.setAttribute("id","orange-spinner");
orangeSpin.setAttribute("id", "blue-spinner");
blueSpin = document.getElementById("blue-spinner");
orangeSpin = document.getElementById("orange-spinner");
blueSpin.addEventListener("click", blueSpinClick);
orangeSpin.addEventListener("click", orangeSpinClick);
}
document.getElementById("orange-spinner").addEventListener("click", orangeSpinClick);
});
h1, h2 {
font-weight: bold;
text-align: center;
font-size: 45px;
font-family: 'VT323', monospace;
margin: 15px;
}
#blue-spinner {
color: blue;
}
#orange-spinner {
color: goldenrod;
}
<script src="https://use.fontawesome.com/releases/v5.0.2/js/all.js"></script>
<html>
<body>
<h1 id="h1">Click Something:</h1>
<h2 id="blue-spinner"><i class="fa fa-cubes fa-spin" aria-hidden="true"></i></h2>
<h2 id="orange-spinner"><i class="fa fa-cubes fa-spin" aria-hidden="true"></i></h2>
</body>
</html>

Categories