News:

The anti-spam plugins have stopped being effective. Registration is back to requiring approval. After registering, you must ALSO email me with your username, so that I can manually approve your account.

Main Menu

Not-working Javascript

Started by Miluette, July 25, 2008, 01:48:59 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Databits

That would simply mean that the code to show it isn't written correctly too. I've done the same thing your doing many many time for things on our ecommerce system for stuff like order editing. It's not really that hard, just need to get the hang of it.

First of all though, I tend to write things a little differently:


...
<head>
  ...
  <script language="javascript" type="text/javascript">
    MyWebsiteName = {};
    MyWebsiteName.toggleContent = function(elementId) {
      var div = document.getElementById(elementId);
      if (!div)
        return false;
      if (div.style.display = 'none')
        div.style.display = '';
      else
        div.style.display = 'none';
      return false;
    }
  </script>
  ...
</head>
<body>
  ...
  <a href="#" onclick="return MyWebsiteName.toggleContent('link1_content');">Link Name</a>
  <div id="link1_content" style="display: none">
    Text content/other html and stuff here...
  </div>
  ...
</body>
...


A few things to note which you may or may not already know. The portion "link1_content" is the div's id. In HTML an id is supposed to be unique to each element, meaning that you don't want to ever have it repeating. Secondly, this code doesn't just open it, it checks to see what the status is for the div and toggles the hiding on or off depending on its state. The weird object stuff "MyWebSite" is a form of name spacing to keep the javascript from being interfered with from other scripts you may add. I also tend to have a habit to always place my JS into onclick handlers rather than the href of the element, and to always have it return "false" to the element telling it not to proceed on to the link contained in href. Finally, just in case the JS fails to do that the "#" will stop it anyhow.

Most the stuff can just be renamed to whatever you like, such as the "MyWebSite" and "link1_content" stuff. I'd also advise that if you wish to style the elements your using, not to use the id's set for styling (even though you can). It's a bad habit to get into. Much more appropriate to use a class in that case in addition to the id element.
(\_/)    ~Relakuyae D'Selemae
(o.O)    
(")_(")  [Libre Office] [Chrome]