3

I am a javascript beginner, but I have implemented this code elsewhere and it worked. Did I overlook something obvious?

https://jsfiddle.net/x3oj787q/1/

html:

<a href="javascript:toggle_visibility('div');">help</a>

<div id="div"style="display: none;">
help
</div>

js:

function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'block')
      e.style.display = 'none';
   else
      e.style.display = 'block';
}
mzrt
  • 55
  • 7

1 Answers1

1

Your code is perfect, but you are creating your function in the onLoad of the page which means its out of scope when you call it from your a href tag. If you compare your Fiddle with @dtsq, you'll notice if you click the JAVASCRIPT button that the Load Type is onLoad for yours, and No wrap - in <body> for his.

No wrap - in <body> tells the browser to not wrap your js code and to place it in the body.
Notice that No wrap - in <head> would work just fine as well.

onLoad tells the browser to wrap the code so it will run in the onLoad window event. You said you implemented this code elsewhere and it worked. When you add this plain javascript code to the head or body section, it works fine. But I'm willing to bet you're trying to place this code in a JQuery block or other onLoad area which causes the issue due to scope.

Ageonix
  • 1,748
  • 2
  • 19
  • 32