I have a problem with Javascript: I'm trying to increment a number which is a string, so I need to parse it, increment the value, and assign that number to the value in the field. But I don't understand why this code doesn't work properly:
<button type="button" onclick="dec()" name="less" style="background-color: orange;border:none;">-</button>
<script>
function dec() {
var x = parseInt(document.getElementById("num").value, 10);
x--;
document.getElementById("num").value = x;
}
While the number is in a div like this:
<div id="num" style="display:inline;">0</div>
Where is the error?
For one hand, if you want to increment the value you need to do x++ instead of x--. And after that, I think you will fix it with:
document.getElementById("num").innerHTML= x;
Because a div does not have a value property.
Just use
document.getElementById("num").innerHTML
instead
Related
I am trying to add a text slider, where basically a very long text box extends out of the view, and when a button is pressed margin is added so more text can be read. I do not know how to make a button that adds margin without exponentially increasing it each time.
<div class='long'>
<div class='container'>
<button type="button" onclick="display()">Add left margin</button>
<p id="myID">This is demo text.</p>
<script>
function display() {
var e = document.getElementById("myID").style.marginLeft += 1 document.getElementById("myID").style.marginLeft;
}
</script>
After a few clicks, this starts to increase the margin insane amounts. I believe it is because the 1 is not 1px, but some other unit which makes it add up insanely quick. SO I want to have a button that adds 1px of margin per click, so it smoothly adds margin instead of a big unuseable jump.
My hypothesis is that you need to get the margin value, store it, then add it to a string that has 'px' at the end then update the margin with it?
You are correct with your thoughts. Store the margin value in a variable outside the function, and increase it by one each time.
The style.marginLeft returns 1px and not 1 which means you cannot increment to it.
var margin = 1;
function display() {
document.getElementById("myID").style.marginLeft = ++margin + "px";
}
<div class='long'>
<div class='container'>
<button type="button" onclick="display()">Add left margin</button>
<p id="myID">This is demo text.</p>
</div>
</div>
The parseInt and parseFloat functions will return numeric value for marginLeft (i.e. without the trailing 'px' that is causing your issue).
function display() {
let el = document.getElementById("myID");
el.style.marginLeft = `${parseInt(el.style.marginLeft)+1}px`;
}
The problem is that happen string concatenation when you use the + operator
You have to convert the value returned from element.style.marginLeft to a number. You can call the Number() function or use the + operator immediately attached how in my solution. Another problem could be that the value returned is like that 1px for example and to increment it you have to parse it, I used split function
function display() {
let currentMarginValue = +document.getElementById("myID").style.marginLeft.split('px')[0];
console.log(currentMarginValue)
var e = document.getElementById("myID").style.marginLeft = currentMarginValue + 1 + "px" ;
}
you may need one counter that will increase in every click. please refer below code
<script>
let count = 0;
function display() {
document.getElementById("myID").style.marginLeft = ++count+"px";
}
</script>
Please keep in mind I am a beginner. It would be very helpful if you could avoid complicated terminology. The issue is that I cant give buttons specific functions. I tried using id and name. I thought it would have been easier if I had the typewriter effect go after pre-existing text but it didn't work and both inputs (buttons) use the second command. All I really need is a way to link the buttons to a specific function.
I originally didn't plan on using the method of having the 1 and 2, so if you have a method which is only typewriter that would work for me as well.
var i = 0
var x = document.getElementById("button1")
var txt = 'button 1';
var speed = 80;
function typeWriter() {
if (i < txt.length) {
document.getElementById("button1").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}[]
var i = 0
var x = document.getElementById("button2")
var txt = 'button 2';
var speed = 80;
function typeWriter() {
if (i < txt.length) {
document.getElementById("button2").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}[]
<div id="container">
<h1>name</h1>
<button style="font-size:25px" onclick="typeWriter()" id="#button1">button number
1</button>
<button style="font-size:25px" onclick="typeWriter()" id="#button2">Button number 2</button>
<h1 id="button1"> l</h1>
<h1 id="button2"> 2 </h1>
<h3 style="color:white;"></h3>
Instead of creating a function for each button, you can reuse the same function and pass it the text and target element, like so:
const speed = 80;
function typeWriter(elementId, text, i = 0) {
const element = document.getElementById(elementId)
if (i < text.length) {
element.innerHTML += text.charAt(i);
setTimeout(() => typeWriter(elementId, text, ++i), speed);
}
}
<div id="container">
<h1>name</h1>
<button style="font-size:25px" onclick="typeWriter('button1', 'some text for button 1')" id="#button1">button number
1</button>
<button style="font-size:25px" onclick="typeWriter('button2', 'some text for button 2')" id="#button2">Button number 2</button>
<h1 id="button1">l </h1>
<h1 id="button2">2 </h1>
<h3 style="color:white;"></h3>
OK so I think you want certain text, associated with a certain button somehow, to be "typed out" in the h1 tags like a typewriter. Let me know if its something else. If so, you need to add parameters to the function, instead of defining it twice, like the following:
function doTheTyping(id, txt) {
var speed = 80;
var i = 0
var el = document.getElementById(id);
function typeWriter() {
if (i < txt.length) {
el.innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
if(el) typeWriter();
}
$button1.onclick = function() {
doTheTyping("button1", "button 1");
};
$button2.onclick = function() {
doTheTyping("button2", "button 2");
};
<div id="container">
<h1>name</h1>
<button style="font-size:25px" id="$button1">button number
1</button>
<button style="font-size:25px" id="$button2">Button number 2</button>
<h1 id="button1"> l </h1>
<h1 id="button2"> 2 </h1>
<h3 style="color:white;"></h3>
</div>
a parameter is like a variable that changes for each function. Notice now there is a parent function, doTheTyping, which has all of the variables (especially i) reset, and within that function itself does the setTimeout start (and increment i), but before i was being incremented by one of the buttons, and by the time it was done, no others would work.
The problem before was that the same variables were being defined twice. If a function or variable has the same name as another one, it has to be renamed, if a different result is expected for it, or it can be reduced to one function that can have different behavior based on the parameters.
Another thing is I noticed the buttons themselves were assigned IDs, but those were never used, so in general the onclick events were moved into a JavaScript tag, to give some more flexibility, instead of having everything inside of the quotes on the HTML page itself
Let me know if you have any questions
You can use a common parametric function called by each button.
Something like that:
function toButton1() {
typeWriter('button 1', 'button 1', 0, 80);
}
function toButton2() {
typeWriter('button 2', 'button 2', 0, 80);
}
function typeWriter(id, txt, i, speed) {
if (i < txt.length) {
document.getElementById(id).innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter(id, txt, i, speed), speed);
}
}
<button style="font-size:25px" onclick="toButton1()">button number 1</button>
<button style="font-size:25px" onclick="toButton2()">Button number 2</button>
<h1 id="button1"> l</h1>
<h1 id="button2"> 2 </h1>
Live Demo: https://stackblitz.com/edit/js-ge9sm8
Since you're new to programming I'll do my best to answer this as clearly as I can. Below you will find a solution to your question, but note that there are many other possible (and probably better) solutions you could come up with.
Most of the changes to the javascript code are explained in the comments that correspond to the particular lines, but there are a few things I want to explain first:
I changed your uses of var to either let or const. These are ways to declare variables introduced with one of the more recent versions of JavaScript, and essentially they are safer ways of declaring variables than var. The main difference between let and const is that varibales defined with the const keyword are constant, meaning they cannot be assigned a different value later on in the code. This is fine for the txt, speed, and button variables as you don't need to change them later on, but note that for i, which you're changing within the main writing function I used let, telling the engine that this is a variable that is expected to change. However, this is mostly a thing of personal preference, and it's ok to use var instead.
I'm not sure if you're familiar with parameters, but essentially they allow you to pass values into a function to change how that function acts. They're defined in the parenthesis ("(...)") after the function name and can then be used anywhere within the body of that function. In this example I'm using them to pass the number of the button, so that I can use the number to adapt the text and get the appropriate element. Notice that in the HTML code, I pass the number 1 and 2 to the function in the onclick handle, to do just that
/**
* Run a typewriter effect for the element associated with the index parameter passed
* into the function.
*
* #param {Number} index The index of the element to associate the animation with
*/
function typeWriter(index) {
let i = 0
// I use the ` symbol here as it allows me to insert a varibale into the string.
// When I then surround [index] with ${} it tells the engine to grab the current
// value of the [index] variable and replace the "${index}" definition with its
// current value. That way this line generates a different text based on what
// index is passed in as a parameter
const txt = `button ${index}`;
const speed = 80;
// The logic for using the backticks (`) and the ${} here is the same as in the
// "const txt = " line above. Inserting the current value of index into the string
// means that this line fetches a different element based on what is provided as the
// index parameter of the function.
const button = document.getElementById(`button${index}`)
// Since the above line gets the element dynamically based on the input it is possible
// that the input will not correspond to an element. If that's the case then button
// will be [null] and we want to just bail out of this whole function and not do
// anything else
if (!button) { return }
// Here I reset the innerHTML of the element. It's up to you if you want to do this
// or just keep adding to the text already in the element, but I found this visually
// more pleasant.
button.innerHTML = ""
// Here I just wrapped the code you had in the [typewriter] function before inside a
// new nested function so that you can still call it from the [setTimeout] call
function writeLetter() {
// As above we first ensure that [button] is a valid element before we do
// anything else.
if (!button) { return };
if (i < txt.length) {
button.innerHTML += txt.charAt(i);
i++;
setTimeout(writeLetter, speed);
}
}
// Here I just need to call the above defined function once to kick off the
// writing effect.
writeLetter()
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Typewriter</title>
</head>
<body>
<div id="container">
<h1>Typewriter</h1>
<button style="font-size:25px" onclick="typeWriter(1)" id="#button1">button number 1</button>
<button style="font-size:25px" onclick="typeWriter(2)" id="#button2">Button number 2</button>
<h1 id="button1">1</h1>
<h1 id="button2">2</h1>
</div>
I hope that was helpful. Of course if you have any questions feel free to comment on my post and I or someone else will do our best to answer. Good luck in your coding career :)
-- Jakub
I have a hidden input field, wich has the value 0:
<input type="hidden" class="test" value="0" />
Now I added a button with some JS to add 0.5 to the value each time the button is clicked:
<a class="addition-input">Click me</a>
Here is the JS part:
$('a.addition-input').click(function(event) {
event.preventDefault();
var currentValue = parseInt($('input.test').val());
var step = 0.5;
var newValue = currentValue + step;
$('input.test').val(newValue);
});
So, the first time i click the link/button, the value gets from "0" to "0.5".
But then, when I click the link/button the second time, it won't change, it just stays "0.5".
I think that jQuery doesn't get the new input value by the second time click, it probably thinks the value is "0".
How can I fix that?
Update:
Here's the fiddle: https://jsfiddle.net/m7pvjrve/1/
Use
var currentValue = parseFloat($('input.test').val());
instead of
var currentValue = parseInt($('input.test').val());
parseInt() converts 0.5 to 0 everytime and the value you get is 0.5 which is actually the step value
Demo: http://jsfiddle.net/GCu2D/657/
Here is simple javascript code which has 3 function Increment(), Stop(), Start().
var value = 0;
var end;
function Increment(){
value++;
document.getElementById('counter').innerHTML = 'Value: ' + value + '<br />';
}
end = setInterval(Increment, 1000);
function Stop(){
clearInterval(end);
}
function Start(){
end = setInterval(Increment, 1000);
}
<p id="counter"></p></br>
<div>
<input id= "btn1" type="button" value="Stop" onclick="Stop()">
<input id = "btn2" type="button" value="Start Again" onclick="Start()">
</div>
How can I manually configure the value; like I would enter a desired value and it will start from that value.
How can I set a threshold value, after crossing the threshold value, the corresponding box/circle will change the color.
Thanks, Kind Regard,
If you mean how could you on the code side set the value, then you would simply change the var value = 0 line to whatever value you want. If you want the user to be able to set the value, then you would use an input to get the user value and then set that as the var value =.
In your script, add a line in Increment() like "if (value >= _) {" with your threshold value in the blank, and then add your color-change code after the bracket.
You want to add an input field that allows the user to set an initial value. I also don't recommend writing inline JavaScript - take a look into the subject of unobtrusive JavaScript.
Here's how your startCounting() should look like:
// Hold our counter info
var counter = {
currValue: 0,
interval: null
};
function startCounting() {
// Set the current value if provided
counter.currValue = startValueField.value || 0;
counter.interval = setInterval(increment, 1000);
}
I'll leave adding the threshold value as an exercise. It's the same idea.
FIDDLE
Here's my code in javascript:
function length(inputLength){
this.inputLength = inputLength;
document.getElementById('view').innerHTML = inputLength.length;
}
Normally, when I press a key, a counter is incremented and when I delete a char with the backspace key, the counter is decremented.
The problem is when I delete a char, the count is incremented by 1 too then is decremented normally.
Try this code by using the "onkeydown" event.
Can you help me?
Why not simplify it and just do this :
function calcLength(elem) {
document.getElementById('output').innerHTML = elem.value.length;
}
Where elem is the input. Using elem.value.length will get the length of the content within the input.
An example of the HTML would be this
<input id="testing" value="" onkeyup="calcLength(this)" />
Length = <span id="output"></span>
Working example here