1

I am trying to write a simple toggle function in Javascript. What it does is take an element, a style name, and a desired value. If the current value of that style on the element is the empty string, that means it hasn't been set, so we set it to the given value. Otherwise, set it to the empty string to disable it.

My code is below:

function toggleStyle(el, styleName, value) {
  if (el.styleName === '')
  {
    el.styleName = value;
  }
  else
  {
    el.styleName = '';
  }
}

However, I'm unsure how I call this function if I want to toggle the visbility of a box. I know to directly change the visibility: I would normally do:

var box = document.getElementById("box");
box.style.display = "none";

But how would I call my toggleStyle to do this? I've tried writing:

toggleStyle (box, display, "none");
toggleStyle (box, style.display, "none");
toggleStyle (box.style, display, "none");

but nothing seems to work.

user6854626
  • 47
  • 1
  • 5
  • because you are looking for a variable `display`, an object style.... use quotes and bracket notation – epascarello Dec 06 '17 at 02:06
  • See this question about setting object properties where the property name is dynamic: https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable – nnnnnn Dec 06 '17 at 02:16

3 Answers3

2

bracket notation is what you need and you need to pass strings.

function toggleStyle(el, styleName, value) {
  if (el.style[styleName] !== value) {  //better to check that it is not the value you have
    el.style[styleName] = value;
  } else {
    el.style[styleName] = '';
  }
}

var btn = document.querySelector("button")
var div = document.querySelector("#foo")
btn.addEventListener("click", function () {
  toggleStyle(div, "display", "none")
});
<button type="button">Click Me</button>
<div id="foo">FOO</div>

Where would this fail? Color codes are one thing, but this is the basic step in the right direction.

epascarello
  • 204,599
  • 20
  • 195
  • 236
0

You should write it like this instead:

function toggleProp(obj, prop, value){
    obj[prop] = obj[prop] ? "" : value; 
}

toggleProp(box.style, "display", "none");

You should also learn how to use the debugger:

enter image description here

From this we can see that it was because the variable display is not defined before using it.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
0

Two things:

First, change your toggleStyle function so that it modifies the element's style property directly, and use bracket notation to dynamically access the property element of the style object:

function toggleStyle(el, styleName, value) {
    if (el.style[styleName] === '') {
        el.style[styleName] = value;
    } else {
        el.style[styleName] = '';
    }
}

Second, pass a string of the style property when you use toggleStyle:

toggleStyle(box, "display", "none"); // display needs to be in quotes
Christian Santos
  • 5,386
  • 1
  • 18
  • 24