David Rickard
David Rickard

Reputation: 11

Script to Show/Hide Content Requires Two Clicks to Execute First Time

We're using the following code to show/hide content when an image is clicked:

  function toggle(image,list)
  {
    var listElementStyle=document.getElementById(list).style;
    if (listElementStyle.display=="none")
    {
      listElementStyle.display="block";
      document.getElementById(image).src="images/down.png";
      document.getElementById(image).alt="Close list";
    }
    else
    {
      listElementStyle.display="none";
      document.getElementById(image).src="images/up.png";
      document.getElementById(image).alt="Open list";
    }
  }

The function is invoked like this:

<p>
<img src="images/up.png" alt="Open List" id="img39384" onClick="toggle('img39384','ul39384');">Agriculture
<ul id="ul39384" class="catList">
<li>
<a href="databases.jsp?cat=39386">Agriculture - Most Useful</a>
</li>
</ul>
</p>

The first time an "up.png" is clicked, it takes two distinct click to fire-off the script and show/hide content. After that first two-click invocation, a single click will fire the script. This behavior holds true in all browsers--IE, Firefox, Opera, Safari, and Chrome.

What could be causing this behavior?

Upvotes: 1

Views: 714

Answers (4)

Jeremy
Jeremy

Reputation: 363

Give your img a

style="display: block;" 

attribute when the page loads initially.

Upvotes: 0

SLaks
SLaks

Reputation: 887777

Your <ul> element is probably inheriting display: none from a CSS rule.

However, because the element's style wasn't explicitly set (inline), elem.style.display is undefined.

Upvotes: 2

jmar777
jmar777

Reputation: 39669

The display value of the element may not be explicitly "none" to start off with. Try this:

  function toggle(image,list)
  {
    var listElementStyle=document.getElementById(list).style;
    if (!listElementStyle.display || listElementStyle.display=="none")
    {
      listElementStyle.display="block";
      document.getElementById(image).src="images/down.png";
      document.getElementById(image).alt="Close list";
    }
    else
    {
      listElementStyle.display="none";
      document.getElementById(image).src="images/up.png";
      document.getElementById(image).alt="Open list";
    }
  }

Upvotes: 1

Peter Bailey
Peter Bailey

Reputation: 105908

element.style only contains style properties that are defined in the element's style attribute (i.e., style="") and not style properties inherited from <style> blocks or external CSS files.

Read here for an abstracted way to retrieve style information.

Upvotes: 1

Related Questions