A very simple question

So, I’m attempting a project that is a “converter”

it takes input from an input field and upon a button click it converts let’s say feet into meters but that’s not so important. I just wanted to explain what I’m doing.

Anyways you can see in my code that I have a variable called feetToMeters that i’m trying to log upon click while taking in the value of the input field.

Now if I have this entire thing INSIDE the function (let feetToMeters = numberDisplayText.value * 3.281) and try to console log metersToFeet, it works just fine

but if I have (let feetToMeters = numberDisplayText.value * 3.281) OUTSIDE of the function and try to console log feetToMeters it does not work.

from my understanding functions can take in variables from outside of the function but not the other way around? So why am I having this issue?

I’m sure this question has a very simple answer, but it must be flying over my head.

let numberDisplayText = document.getElementById('number-display-text')
let convertButton = document.getElementById('convert-button')

let metersAndFeetParagragh = document.getElementById('meters-and-feet')
let litersAndGallonsParagraph = document.getElementById('liters-and-gallons')
let kilosAndPoundsParagraph = document.getElementById('kilos-and-pounds')

let metersToFeet = numberDisplayText.value / 3.281
let feetToMeters = numberDisplayText.value * 3.281

convertButton.addEventListener('click', function() {

Let us debug this together, try arrow function and let’s see how it goes. Like so:

convertButton.addEventListener('click', () =>  {

All of that code above the event listener is executed once. So feetToMeters is set to whatever value and never changes. So every time you click the button and it runs your event handler, it is just displaying whatever value feetToMeters was initially set to.

What you want to do is set feetToMeters each time you click the button. So you want to execute the code needed to get the value from the input and covert it to meters inside the event handler.

1 Like

This cleared it up a lot, thank you!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.