1

I'm a beginner and I've created an event listener here, that works:

var inpt = document.getElementsByTagName('input')[0];

plus.addEventListener("click", function() {
  if(inpt.style.display === 'none'){
    inpt.style.display = 'block';
  } else {
    inpt.style.display = 'none';
  }
});

but when I assign the value of 'inpt.style.display' to a variable and try again, it doesn't work:

var inpt = document.getElementsByTagName('input')[0];

plus.addEventListener("click", function() {
 var disp = inpt.style.display;
 if(disp === 'none'){
   disp = 'block';
 } else {
   disp = 'none';
 }
});

Why doesn't this work? Thank you!

vsync
  • 118,978
  • 58
  • 307
  • 400
user74843
  • 701
  • 2
  • 10
  • 28

3 Answers3

3

You do not set the the style for the display property but you are simply setting a new value for your variable disp...

disp is a variable pointing to a primitive's value, meaning it does not know that is is "connected" to inpt.style.display, so when you change disp variable, it will never affect inpt.style.display.

It could have only affect it, if it was pointing to an Object, for example:

var disp = inpt.style; // style is an Object which has the "display" property 

You must directly change the display property:

inpt.style.display = 'block';

and so on.


Try this:

var inpt = document.querySelector('input'); // changed to "querySelector"

plus.addEventListener("click", function() {
    inpt.style.display = inpt.style.display === 'none' ? 'block' : 'none';
});
vsync
  • 118,978
  • 58
  • 307
  • 400
0

That variable is a string, therefore when you create a new variable, you just get a copy of a string and don't override the old value. Try this:

var a = "123"
var b = a;
var b = "something else"

Now check the values of b and a. You will see that a hasn't changed.

eddyP23
  • 6,420
  • 7
  • 49
  • 87
0

You're copying the value in inpt.style.display. It's a value, not a reference. Reassigning it will not change the original value.

let testObject = { testField: "hello" };
let testField = testObject.testField;
testField = "goodbye";
console.log(testObject.testField); // "hello"

You can find some more information in this answer: Javascript by reference vs. by value

Steven Goodman
  • 576
  • 3
  • 15