I would like to increase the font size of the paragraph as well as the font size of the number in the button.
I copied and pasted my sizer function from StackOverflow (a few alterations) and thought it would work and still can't get it to work. Can someone help?
Since I've spent so much time on just the first part, as a beginner programmer, I'm wondering what I am missing. Does anyone have any ideas from my code or their experience as to what I might be missing?
Thanks as always.
<html>
<button onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
sizer = function changeFontSize() {
div = document.getElementById("test");
currentFont = div.style.fontSize.replace("pt", "");
div.style.fontSize = parseInt(currentFont) + parseInt(clicks) + "pt";
}
</script>
</html>
Some things here:
I woudn't append two functions to your onclick here. Just append one and call your second function from the first one that gets fired via onclick. That looks a lot more tidy
Don't forget to put var before every variable, without it's not valid JavaScript
I didn't quite understand what you tried with your currentFont variable, so I removed it. It's not necessary and causes the script to not working correctly
<html>
<button onclick='incrementer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
var clicks = 0;
var incrementer = function() {
clicks += 1;
var click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
sizer();
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
div.style.fontSize = parseInt(clicks) + "pt";
}
</script>
</html>
Here's a from-scratch version that does what you're asking for. I'll point out a few things that I did to help you out.
https://codepen.io/anon/pen/VBPpZL?editors=1010
<html>
<body>
<button id="count">0</button>
<p id="test">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</p>
</body>
</html>
JS:
window.addEventListener('load', () => {
const button = document.querySelector('#count');
const paragraph = document.querySelector('#test');
const startingFontSize = window.getComputedStyle(document.body, null)
.getPropertyValue('font-size')
.slice(0, 2) * 1;
let clicks = 0;
button.addEventListener('click', () => {
clicks++;
// this is a template literal
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const fontSize = `${startingFontSize + clicks}px`;
button.innerHTML = clicks;
button.style.fontSize = fontSize;
paragraph.style.fontSize = fontSize;
});
});
The code runs when the page is loaded, so we attach an event listener on the window object listening for the load event.
We then store references to the button and the paragraph elements. These are const variables because their values won't change. This also limits their scope to the containing function.
We get the initial font size for the body element, because in this example we aren't explicitly setting a base font in css so we're just using the one for the document. getComputedStyle is a somewhat expensive operation, and in this case we only need to get it in the beginning because it won't change, so we also store it as a const. The value is returned as a string like "16px" but we need the number, hence the slice and multiplying by one to cast the string into a number. parseInt would also do the same thing.
Notice that clicks is defined with let. This means that the variable can be changed. var still works of course, but in modern practices its best to use const and let when declaring variables. This is partly because it forces you to think about what kind of data you're working with.
We add an event listener to the button element and listen for the click event. First, we increment the clicks variable. Then we declare fontSize using a template literal which adds our new clicks count to the startingFontSize and "px" to get a string.
Finally, the innerHTML value of the button element is updated. Then we update the fontStyle property for both elements.
The issue here is that there is no initial value for the fontSize of your <p> tag so div.style.fontSize returns an empty string.
You can use window.getComputedStyle instead of div.style.fontSize and you will get the current fontSize.
There is already a post explaining this method
https://stackoverflow.com/a/15195345/7190518
You don't have an initial font-size style on your <p> tag, so it div.style.fontSize is always empty. Also, best practice is to always use var when introducing new variables in javascript.
One good trick to help debugging things like these is to use console.log() at various points, and see whats coming out in your browser console. I used console.log(div.style.fontSize) and the answer became clear.
Working below after adding <p style='font-size:12px'>a</p>:
<html>
<button style='font-size:12px;' onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test' style='font-size:12px;'>a</p>
<script>
var clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
var btn = document.getElementById("count");
var newSize = parseInt(div.style.fontSize.replace("pt", "")) + parseInt(clicks);
div.style.fontSize = newSize + "pt";
btn.style.fontSize = newSize + "pt";
}
</script>
</html>
I don't understand the logic of this solution, but you can simplify it avoiding to use a lot of var (anyway always prefer let or const if you don't need to change), using a single function and writing less code.
function increment(e){
const ctrl = document.getElementById('test');
let current = parseInt(e.dataset.size);
current += 1;
e.innerHTML = current;
e.dataset.size = current;
ctrl.style.fontSize = current + 'pt';
}
<button onclick="increment(this);" data-size="20">20</button>
<p id='test' style="font-size:20pt;">A</p>
Related
I was trying to change the color of the background of the web page with a mouse click, below are the lines for the same:
let bodyvar = document.querySelector('body');
bodyvar.addEventListener("click",generate);
function generate(){
bodyvar.style.backgroundColor = "red";
}
When I test individual lines in console it is selecting the body and the function and everything works correctly individually but not on the actual page.
I have just started leaning JS so am not sure what am missing here, will I also need to consider the co-ordinates that the mouse clicks on?
I suspect that the <body></body> is empty. Add some content, or define the width and height.
let bodyvar = document.querySelector('body');
bodyvar.style.minWidth = "100vw";
bodyvar.style.minHeight = "100vh";
bodyvar.addEventListener("click",generate);
function generate(){
bodyvar.style.backgroundColor = "red";
}
Alternatively, I can use <HTML> instead of <body>.
let bodyvar = document.querySelector('html');
bodyvar.addEventListener("click",generate);
function generate(){
bodyvar.style.backgroundColor = "red";
}
I am making a javascript note-taking app. Here is the code so far:
Javascript is:
var inputValue = document.getElementById('myInput');
var input = document.getElementById('myInput');
var button = document.getElementById('myButton');
function run(){
localStorage.setItem('inputer', inputValue);
let p = document.createElement('p');
p.id = 'content';
p.innerHTML = inputValue.value;
document.body.appendChild(p);
}
window.addEventListener('load', () => {
var savedUserData = localStorage.getItem('inputer');
var p2 = document.createElement('p');
p2.innerHTML = savedUserData.value;
document.body.appendChild(p2)
});
And the HTML is:
<input id = "myInput">
<button id = "myButton" onclick = "run();">
Take note:
</button>
It works by stacking notes on top of notes and saving the data in local storage. But for some reason, it does not save the notes correctly. It will stack them but not save them. Also, it says this: "undefined". I would assume that that is because it checks the value of the input first before anything has been in it. And as I am writing this I am thinking that my idea is not going to work because there is mutiple input. So how would I fix this so this so the user can stack notes ontop of notes, and they will all be stored in local storage and come back to the user when the page reloads? Thank you and have a good day!
It seems your first line of code should say:
var inputValue = document.getElementById('myInput').value;
See the code below:
var text=["yuppie", "kkkoseh", "watchdog"];
var messageIndex=0;
function looptext (){
var MessageElement= document.getElementById("happy").innerHTML
var Message=text[messageIndex];
MessageElement=Message;
messageIndex++;
if(messageIndex>=text.length){
messageIndex=0;
}
}
window.onload = function() {
setInterval(looptext, 1000);
};
It doesn't work.
But when I remove .innerhtml at variable MessageElement and set the MessageElement.innerHtml= Message , it works.
Why is it so?
Sorry, I am a newbie learning JavaScript.
Because that's how variables and values work in JavaScript. Imagine variables to be like containers. With
var MessageElement = document.getElementById("happy").innerHTML
the container MessageElement will contain a string. Later on, with
MessageElement = Message;
you simply put a new value in the container, overwriting the previous value/content the container had. But it doesn't have any effect on the location where the previous value was coming from.
But when I remove .innerhtml at variable MessageElement and set the MessageElement.innerHtml= Message , it works.
Now the variable contains a reference to the DOM element and
MessageElement.innerHtml = Message
doesn't assign a new value to the variable (doesn't put a new value in the container), it uses the value of the variable (container).
innerHTML return a string not e pointer to the document.getElementById("happy")'s text node.
try this
var text=["yuppie", "kkkoseh", "watchdog"];
var messageIndex=0;
function looptext (){
document.getElementById("happy").innerHTML = text[messageIndex];
messageIndex++;
if(messageIndex>=text.length){
messageIndex=0;
}
}
window.onload = function() {
setInterval(looptext, 1000);
};
#Felix King is correct.
To test how it is actually behaving I myself tried the below snippet on W3Schools.
And I found:
var MessageElement = document.getElementById("happy") - assigns the element (in my example - http://www.microsoft.com/)
alert(m) thus displays - http://www.microsoft.com/
m.innerHTML = "Atul" - assigns Atul to the element.
However, value of m was still http://www.microsoft.com/ as Felix rightly said - 'MessageElement.innerHtml = Message, doesn't assign a new value to the variable'.
<html>
<head>
<script>
function changeLink()
{
var m = document.getElementById("myAnchor"); //assigns http://www.microsoft.com/
alert(m); //
m.innerHTML = "Atul"
alert(document.getElementById("myAnchor").innerHTML + " new");
document.getElementById('myAnchor').innerHTML=m;
}
</script>
</head>
<body>
<a id="myAnchor" href="http://www.microsoft.com">Microsoft</a>
<input type="button" onclick="changeLink()" value="Change link">
</body>
</html>
Thanks Felix :)
I am trying to make a button that when clicked adds 200 to the value of the p tag. I have looked up my question and clicked on every result, to no avail.Please help. Whenever I click the button it either prints NaN(Not a Number) or 200200200200200 etc.. I need help so that instead of those 2 mess-ups, it adds 200 each time the button is clicked. (addition not concatenation)
Here is my code:
<button onClick="addPoints()">Click to get points!</button>
<p id="counter"></p>
<script>
function addPoints(){
var id=document.getElementById("counter").innerHTML = parseInt(adding);
var adding = id + 200;
}
There is probably a mess-up I am not aware of. Any help will be greatly appreciated!
Your adding variable was assigned after it is used. This code works:
<button onClick="addPoints()">Click to get points!</button>
<p id="counter"></p>
<script>
function addPoints(){
var x = document.getElementById("counter").innerHTML;
document.getElementById("counter").innerHTML = (isNaN(parseInt(x))?0:parseInt(x)) + 200;
}
</script>
What I did here is the function checks the value of the counter <p> tag. If the content is an integer >= 0, add 200. Otherwise, assign an initial value of 0 before adding 200 so that the contents are added and are not concatenated.
change the sequence of code
function addPoints(){
var adding = parseInt( document.getElementById("counter").innerHTML) + 200;
document.getElementById("counter").innerHTML =adding;
}
Try this
function addPoints(){
var sum=parseInt(document.getElementById("counter").innerHTML);
sum = isNaN(sum) ? 0 : sum;
sum += 200;
document.getElementById("counter").innerHTML = sum;
}
You're trying to use the variable adding in parseInt before actually creating it. Try this:
function addPoints(){
var id=document.getElementById("counter").innerHTML;
var adding = id + 200;
document.getElementById("counter").innerHTML = parseInt(adding);
}
convert id to number
function addPoints(){
var id=document.getElementById("counter").innerHTML = parseInt(adding);
var adding = ((id*1) + 200);
}
Scenario:
User enters text "thisisabutton" for ButtonA
User enters text "thisisalongerbutton" for ButtonB
Both buttons dynamically adapt in size to fit text length, thus making them 2 different sizes
I want ButtonA to be the same size as ButtonB (which will determine the size since it's longer than ButtonA).
What is the best approach to do this in Javascript?
<button id="ButtonA" onChange="ResizeButtons();">Hello</button>
<button id="ButtonB" onChange="ResizeButtons();">Worlddddddddddddddd</button>
<script type="text/javascript">
function getWidth(element) {
return parseInt(window.getComputedStyle ? window.getComputedStyle(element,null).getPropertyValue("width") : element.currentStyle.width );
}
function ResizeButtons() {
var buttonA = document.getElementById("ButtonA");
var buttonB = document.getElementById("ButtonB");
buttonA.style.width = "auto";
buttonB.style.width = "auto";
var buttonAWidth = getWidth(buttonA);
var buttonBWidth = getWidth(buttonB);
var maxWidth = (buttonAWidth > buttonBWidth ? buttonAWidth: buttonBWidth) + "px";
buttonA.style.width = maxWidth;
buttonB.style.width = maxWidth;
}
</script>
1) Cross Browser.
2) Resets elements to "auto" before computing, or else they'll never resize after the first character is entered.
3) Avoids re-accessing DOM after getting buttonA and buttonB.
4) Checks while each button is being modified.
EDIT
You may have to put the ResizeButtons(); event on the inputs you're using to change the button content, or better yet, simply run the function ResizeButtons() inside your current script that changes the button content, immediately after the content is changed.
<button id="ButtonA">Hello</button>
<button id="ButtonB" onChange="ResizeButtons();">Worlddddddddddddddd</button>
<script type="text/javascript">
function ResizeButtons()
{
var buttonAWidth = document.getElementById("ButtonA").style.width;
var buttonBWidth = document.getElementById("ButtonB").style.width;
var maxWidth = 0;
if (buttonAWidth >= buttonBWidth){
maxWidth = buttonAWidth;
}
else{
maxWidth = buttonBWidth;
}
document.getElementById("ButtonA").style.width = maxWidth;
document.getElementById("ButtonB").style.width = maxWidth;
}
</script>
While this answer utilizes jQuery the principles are the same as the above answers without a lot of the extra hassle of handling getting a true element width. I by no means am advocating that you should necessarily use jQuery, but I think it illustrates the solution in a more concise fashion.
The user adds a new button by providing a new name.
Calculate the longest button and reset the widths of smaller buttons
The code:
<label for="buttonName">Enter Button Name:</label><input id="buttonName">
<button id="createButton">Create Button</button>
<div id="buttons"></div>
<script type="text/javascript">
$('#createButton').button().click(function(){
var buttonName = $('#buttonName').val();
$('#buttonName').val("");
$('#buttons').append($('<button>'+buttonName+'</button>').button());
var widestButton = 0;
$('#buttons button').each(function(){
widestButton = Math.max($(this).width(), widestButton);
});
$('#buttons button').width(function(){
if ($(this).width() < widestButton)
$(this).width(widestButton);
});
});
</script>
http://jsfiddle.net/PwNUA