www.webdeveloper.com
Results 1 to 3 of 3

Thread: [RESOLVED] What's wrong with my simple JS code?

  1. #1
    Join Date
    Aug 2007
    Location
    New Jersey, US
    Posts
    1,779

    resolved [RESOLVED] What's wrong with my simple JS code?

    Hey guys, I have the following code to show/hide a div on click, but I can't get it working. Does anyone see what's wrong with my code?

    HTML:
    HTML Code:
    <div id="settings">
      <a href="#">settings</a>
      <ul>
        <li><label for="filter-nsfw">Hide NSFW</label> <input type="checkbox" id="filter-nsfw" name="filter-nsfw"></li>
      </ul>
    </div>
    JS:
    Code:
    function toggle(el) {
      (el.style.display == 'block') ? el.style.display = 'none' : el.style.display = 'block';
    }
    
    document.getElementById('settings').getElementsByTagName('a').onclick = function(){
      var settingsList = this.getElementsByTagName('ul');
      toggle(settingsList);
    };
    CSS:
    Code:
    #settings {display: none;}
    Thanks!

  2. #2
    Join Date
    Nov 2010
    Posts
    1,053
    on the face of it, getElementsByTagName will return a collection (similar to an array).

    You can't add an onclick to the collection, you have to loop through it adding the onclick to each element in the collection...

    Code:
    var mylinks=document.getElementById('settings').getElementsByTagName('a');
    for (var i = 0; i < mylinks.length; i++) {
    mylinks[i].onclick = function(){
     // var settingsList = this.getElementsByTagName('ul');// same problem here - you either need to loop through them all or choose one...
    var settingsList = this.getElementsByTagName('ul')[0];  
    toggle(settingsList);
          };
    }
    but the more interesting question would be how is this link ever going to be seen, if it sits inside a div that is hidden in the css on page load?

  3. #3
    Join Date
    Aug 2007
    Location
    New Jersey, US
    Posts
    1,779
    Oh, right, that makes sense. Thanks a lot!

    I thought that because the elements are in the DOM, display:none doesn't matter, but I guess I'm wrong.
    What if I make them visibility:hidden?

    edit: it does seem to work with the element hidden with display:none;
    The new working JS looks like this:

    Code:
    document.getElementById('settings').getElementsByTagName('a')[0].onclick = function() {
    	var settingsList = this.parentNode.getElementsByTagName('ul')[0];
    	toggle(settingsList);
    };
    Thanks again for taking a look!
    Last edited by dtm32236; 10-01-2012 at 09:20 AM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles