I have an input that changes a paragraph's font size. The input changes the size of the paragraph whenever I enter things like "30px". I want it able to change when I only put the number of the size I want without needing to have "px" after it.
I also have 2 buttons next to it saying that adds or subtracts the value, but I cannot figure out how to make them change the value.
Obviously, I'd want this to all work without needing to have "px" after the number, but I can't seem to figure it out.
Any help is appreciated.
My code:
<tr>
<th>Text size (px):
<input id="textSizeInput" type="text" value="20px">
<button id="sizeChanger">Change</button>
<button id="addTen"> 10px</button>
<button id="minusTen">-10px</button>
</th>
</tr>
Javascript for the above code
var changeTextSize = function () {
console.log('in changeTextSize');
var newTextSize = document.getElementById("textSizeInput").value;
document.getElementById("showText").style.fontSize = newTextSize;
}
document.getElementById('sizeChanger').onclick = changeTextSize;
document.getElementById('textSizeInput').onchange = changeTextSize;
CodePudding user response:
Without any data validation or bounds checks:
function increment() {
const input = document.getElementById("textSizeInput");
input.value = Number(input.value) 10;
}
function decrement() {
const input = document.getElementById("textSizeInput");
input.value = Number(input.value) - 10;
}
<tr>
<th>Text size (px):
<input id="textSizeInput" type="text" size="5" value="20"> px
<button id="addTen" onclick="increment()"> 10px</button>
<button id="minusTen" onclick="decrement()">-10px</button>
</th>
</tr>
CodePudding user response:
You can add an click
event listener to each of the buttons which calls a function and increments the value of the input by a certain number.
To increment the value, get the value of the input, split by "px"
, get the first item, increment it by the value, concatenate "px"
then assign back to the input's value property:
var input = document.getElementById("textSizeInput")
var changeTextSize = function() {
console.log('in changeTextSize');
var newTextSize = input.value;
document.getElementById("showText").style.fontSize = newTextSize;
}
document.getElementById('sizeChanger').onclick = changeTextSize;
document.getElementById('textSizeInput').onchange = changeTextSize;
function increment(value){
let currentValue = input.value.split("px")[0]
input.value = currentValue value "px";
}
<tr>
<th>Text size (px):
<input id="textSizeInput" type="text" value="20px">
<button id="sizeChanger">Change</button>
<button id="addTen" onclick="increment(10)"> 10px</button>
<button id="minusTen" onclick="increment(-10)">-10px</button>
</th>
</tr>
<p id="showText">Hello World!</p>