www.webdeveloper.com
Results 1 to 6 of 6

Thread: javascript accordion using DOM + CSS (no jQuery)

  1. #1
    Join Date
    Dec 2010
    Posts
    9

    Question javascript accordion using DOM + CSS (no jQuery)

    I'm trying to create a simple javascript accordion that will let me show/hide <p> paragraphs when I click on an <h2>. When the page is loaded, the <p> are automatically hidden. (This part works ok). When you click on the H2, I want the paragraphs to then appear. Something with the h2 onclick event or either the way I'm calling the DOM is not working. I was hoping for some help/guidance.

    HTML:
    Code:
    <div id="content">
    <h2>Header 1</h2>
    <p>Here is my header 1 paragraph</p>
    <h2>Header 2</h2>
    <p>Here is my header 2 paragraph</p>
    <h2>Header 3</h2>
    <p>Here is my header 3 paragraph</p>
    </div>
    CSS:
    Code:
    #content h2 {margin-bottom: 0;}
    #content p {margin-top: 0;}
    JAVASCRIPT:

    Code:
    window.onload = function() {
    
    var sectionDiv = document.getElementById('content');					
    var triggers = sectionDiv.getElementsByTagName('h2');				
    var paras = sectionDiv.getElementsByTagName('p');						
    
    
    for (var i = 0; i<paras.length;i++) {					
    paras[i].style.display = "none";				
    		}		
    	
    for (var i = 0; i<triggers.length;i++) {							
    	triggers[i].style.display = "block";						
     	triggers[i].onclick = function () {							
    		if (this.nextSibling.style.display == "none") {				
    		this.nextSibling.style.display = "block";
    				} else { 									
    this.nextSibling.style.display = "none";							}
    }	
    }	
    }
    Thanks!

  2. #2
    Join Date
    Apr 2003
    Location
    Netherlands
    Posts
    21,654
    White space in the DOM
    This can be solved using:
    Code:
    for (var i = 0; i<triggers.length;i++) {							
    	triggers[i].style.display = "block";						
     	triggers[i].onclick = function () {
            var sibling=(this.nextSibling.nodeType==3)? this.nextSibling.nextSibling : this.nextSibling;
    		if (sibling.style.display == "none") {				
    		sibling.style.display = "block";
    				} else { 									
    sibling.style.display = "none";							}
    }	
    }
    At least 98% of internet users' DNA is identical to that of chimpanzees

  3. #3
    Join Date
    Mar 2009
    Posts
    590
    Here is an adaptation of something I did before. However, it does the opposite in that the p elements are visible upon start up.

    Code:
    <html> 
    <head> 
    <script type = "text/javascript">
         var fred; 
         function createControl(){
         var x = {section: []};  //create generic object containing the section array
    
         var i, num, tmp, v, func;
         v = document.body;
         num = -1;
         for (i =0; i < v.childNodes.length; i++){  //search for all h2 elements place and store ref as new obj in section arr
    	 if(v.childNodes[i].tagName == 'H2'){
    	     num++;
    	     tmp = {p: []};
    	     tmp.header = v.childNodes[i];
    	     tmp.setting = "block";
    	     x.section[num] = tmp;
    	 }
    	 else if(v.childNodes[i].tagName == 'P'){  //store ref to p elements in x.section[].p array
    	     x.section[num].p.push(v.childNodes[i]);
    	 }
         }
    
         x.doShift =function(offset){ //determine current setting "none" or "block" from x.section[].settting prop
    	 var len = x.section[offset].p.length;
    	 var j, status;
    	 if(x.section[offset].setting == "block"){
    	     x.section[offset].setting = "none";
    	 }
    	 else{x.section[offset].setting = "block";
    	 }
    	 status = x.section[offset].setting;
    	 for(j = 0; j < len; j++){ //change display setting for p elements
    	     x.section[offset].p[j].style.display = status;
    	 }
         }
    
         //----------------------------------------
    
         x.toggle = function(e){  //determine which, if any of the H2 elements was the click source ==x.section[].header
         var targ;
            if (!e){
                var e=window.event;
            }
            if (e.target){
                targ=e.target;
            }
            else if (e.srcElement){
                targ=e.srcElement;
            }
            if (targ.nodeType==3){
                targ = targ.parentNode;
            }
            
    	var i, len, flag = -1;
         len = x.section.length;
    	for (i = 0; i < len; i++){
    	    if(x.section[i].header === targ){
    	    flag = i;
    	    break;
                }
            }
         if(flag == -1){return;} //if the click didn't originate from an h2 return
    
         x.doShift(flag); //change the display property
         }
    
    			
         return x;
     }
    
    
    //var fred;	 
    window.onload = function(){ fred = createControl();} 	    
    	     
    	 
            
    </script> 
    </head> 
    <body onclick ="fred.toggle(event)"> 
    <h2> This is the first</h2>
    <p>first of first.</p>
    <p>second of first</p>
    <p>third of first</p>
    <h2>Second</h2>
    <p>first of second</p>
    <p>second of second</p>
    </body> 
    </html>

  4. #4
    Join Date
    Dec 2010
    Posts
    9
    Quote Originally Posted by Fang View Post
    White space in the DOM
    This can be solved using:
    Code:
    for (var i = 0; i<triggers.length;i++) {							
    	triggers[i].style.display = "block";						
     	triggers[i].onclick = function () {
            var sibling=(this.nextSibling.nodeType==3)? this.nextSibling.nextSibling : this.nextSibling;
    		if (sibling.style.display == "none") {				
    		sibling.style.display = "block";
    				} else { 									
    sibling.style.display = "none";							}
    }	
    }
    I think this is probably close to what I'm looking for but when I try this code, it doesn't work...? The paragraphs are automatically display and the h2 headers don't do anything on click.

    I am also trying to understand this line of code:
    Code:
    var sibling=(this.nextSibling.nodeType==3)? this.nextSibling.nextSibling : this.nextSibling;
    The "this" is the h2. It's next sibling is the p tags. You are telling it to grab all the paragraphs who's nodeType is 3 for text nodes? What I'm not sure is what the next bit of code means....
    "? this.nextSibling.nextSibling : this.nextSibling;"

  5. #5
    Join Date
    Apr 2003
    Location
    Netherlands
    Posts
    21,654
    It's next sibling is the p tags
    Only in IE.
    Other browsers insert text nodes, hence this.nextSibling.nextSibling, which will get the node after the text node, the p element.

    Another method:
    Code:
    window.onload = function() {
    
    var sectionDiv = document.getElementById('content');					
    var triggers = sectionDiv.getElementsByTagName('h2');				
    var paras = sectionDiv.getElementsByTagName('p');						
    
    
    for (var i = 0; i<paras.length;i++) {					
        paras[i].style.display = "none";				
        }		
    	
    for (var i = 0; i<triggers.length;i++) {							
        triggers[i].style.display = "block";						
        triggers[i].onclick = function () {				
            n = this;
            do {
            	n = n.nextSibling;
                }
            while (n && n.nodeType != 1);
        if (n.style.display == "none") {				
            n.style.display = "block";
            } 
        else { 									
            n.style.display = "none";							}
            }	
        }	
    }
    Last edited by Fang; 12-05-2010 at 01:43 PM.
    At least 98% of internet users' DNA is identical to that of chimpanzees

  6. #6
    Join Date
    Dec 2010
    Posts
    9

    Thumbs up

    Quote Originally Posted by Fang View Post
    Only in IE.
    Other browsers insert text nodes, hence this.nextSibling.nextSibling, which will get the node after the text node, the p element.

    Another method:
    Code:
    window.onload = function() {
    
    var sectionDiv = document.getElementById('content');					
    var triggers = sectionDiv.getElementsByTagName('h2');				
    var paras = sectionDiv.getElementsByTagName('p');						
    
    
    for (var i = 0; i<paras.length;i++) {					
        paras[i].style.display = "none";				
        }		
    	
    for (var i = 0; i<triggers.length;i++) {							
        triggers[i].style.display = "block";						
        triggers[i].onclick = function () {				
            n = this;
            do {
            	n = n.nextSibling;
                }
            while (n && n.nodeType != 1);
        if (n.style.display == "none") {				
            n.style.display = "block";
            } 
        else { 									
            n.style.display = "none";							}
            }	
        }	
    }
    Thank you SO much! That works!! I appreciate your help!

Thread Information

Users Browsing this Thread

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

Tags for this Thread

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

"

"

X vBulletin 4.2.2 Debug Information

  • Page Generation 0.10345 seconds
  • Memory Usage 2,913KB
  • Queries Executed 15 (?)
More Information
Template Usage (34):
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (9)bbcode_code
  • (3)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (6)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (6)postbit
  • (6)postbit_onlinestatus
  • (6)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (73):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_postinfo_query
  • fetch_postinfo
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates