Bas Goorden
Bas Goorden

Reputation: 9

Why is the javascript not working on all referenced IDs

I'm working on a Joomla website. Now I need a slider to change when someone hovers over a text link. I'm using some javascript. It's working on the first div with the id=slider, but not on the second div with id=slider in the article. Can someone tell me why it's doing this?

I'm using the following code in a custom code module for Joomla.

<html>
  <head>
    <meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
    <title>Untitled Page</title>
    <style type="text/css" media="screen">
      <!--
      .boxVisible {
        background-color: #eee;
        display: block;
        padding: 5px;
        float: left;
        border: solid 1px #000040
      }
      .boxHidden {
        display: none;
      }
      -->
    </style>
    <script type="text/javascript">
      <!--
      function showHide(slider) {
        theBox = document.getElementById(slider);
        if (theBox.className == "boxVisible") {
          theBox.className = "boxHidden";
        } else {
          theBox.className = "boxVisible";
        }
      }
      //-->
    </script>
  </head>
  <body bgcolor="#ffffff">
    <p><a href="link.html" onmouseover="showHide('slider'); return false;">More</a></p>
  </body>
</html>

This is my article:

<div id="slider" class="boxVisible">{loadposition slider1}</div>
<div id="slider" class="boxHidden">{loadposition slider2}</div>
<p><br /><br /><br /> {loadposition java}</p>

Upvotes: 0

Views: 85

Answers (3)

Nicholas Murray
Nicholas Murray

Reputation: 13529

Id's should be unique on a page.

You could wrap your slider divs in a wrapper div and use that as basis for iterating through your sliders something like this.

HTML:

 <div id="sliders">
  <div class="boxVisible"></div>      
  <div class="boxHidden"></div>  
</div>

Javascript:

function showHide2(slider) {
var sliders = document.getElementById(slider).getElementsByTagName("div");

for (s in sliders) {
    if (sliders.hasOwnProperty(s)) {
        if (sliders[s].className == "boxVisible") {
            sliders[s].className = "boxHidden";
            alert('changed visible');
        } else if (sliders[s].className == "boxHidden") {
            sliders[s].className = "boxVisible";
            alert('changed hidden');
        }
    }
}
}

showHide2("sliders");

Upvotes: 0

eyurdakul
eyurdakul

Reputation: 912

the dom elements can't have the same id's! if you give the same id to the multiple dom elements, javascript will take only the first one.

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

IDs must be unique identifiers. For multiple elements, use class names.

Upvotes: 1

Related Questions