Author Options:

Javascript toggle element code Answered

I am trying to add a bit of interactivity to my personal website and have seen several example pieces of code for toggling elements. I tried the code that everyone shows me, but I have two problems:

@ It doesn't toggle.

@ The element starts out shown.

I've looked through every part of my code and can't find a single fault. I would really appreciate any help. Here is the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  <meta content="text/html; charset=ISO-8859-1"
  <script type="text/javascript">
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'none' ) {
el.style.diplay = 'none';
else {
el.style.display = ''
  <title>Test doc</title>
<a href="javascript: toggle('greet');">click</a>
<p id="greet">Hello</p>

I read something about jQuery on the site - Do I have to download it?



8 years ago

Okay, as for why the "Hello" is displayed initially, it's because you don't have any CSS definition for what to do with id="greet" tags. Therefore, on load that paragraph uses the default

style, which is normal display. You need to specify an initial style if you want to do something different.

I am not sure "id" is the correct attribute to be using here. ID is meant to be a unique identifier for one particular element of a document -- that is, this paragraph here, and not that other one. I think you might want to be using "class" to identify a particular kind of paragraph with a custom display configuration.

dungeon runnerkelseymh

Answer 8 years ago

I finally figured it out - I should have been using toggle('greet'), in single quotes. I think it was because it was mistaking it for text instead of an id.



8 years ago

Are you testing this by loading it into your browser through an HTTP server, or as "Open file" on your local machine? My experience with Firefox is that the two do not always produce identical results.

kelseymhdungeon runner

Answer 8 years ago

No. Opening a file as "file" is going to be the same anywhere. Macs have a "built-in" Web server for local access, so I saved your file and tried accessing it that way (using the URL http://localhost/~MYUSERNAME/js_test.html).

I see the same behaviour either way, and I think I might know part of the reason why, which I'll put up as a top-level response.


8 years ago

It's starting out shown because the default value of el.style.display is to show it. If that isn't what you want, you need to set up the element so its initial state is to be hidden.

(My Javascript and CSS are minimal. Some day maybe I'll fix that, but I really haven't needed/wanted either so far.)


8 years ago

It appears to me that (obj) is undefined.



Answer 8 years ago

Hi, lemonie. "obj" is the function argument (function toggle(obj)). JavaScript doesn't use or require type declarations.