Advertisement
GWibisono

ddacordian.js v2

Aug 9th, 2013
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.    
  2.  
  3.     //** Accordion Content script: By Dynamic Drive, at http://www.dynamicdrive.com
  4.     //** Created: Jan 7th, 08'. Last updated: June 7th, 2010 to v1.9
  5.      
  6.     //Version 1.9: June 7th, 2010':
  7.     //**1) Ajax content support added, so a given header's content can be dynamically fetched from an external file and on demand.
  8.     //**2) Optimized script performance by caching header and content container references
  9.      
  10.      
  11.     var ddaccordion={
  12.             ajaxloadingmsg: '<img src="loading2.gif" /><br />Loading Content...', //customize HTML to output while Ajax content is being fetched (if applicable)
  13.      
  14.             headergroup: {}, //object to store corresponding header group based on headerclass value
  15.             contentgroup: {}, //object to store corresponding content group based on headerclass value
  16.      
  17.             preloadimages:function($images){
  18.                     $images.each(function(){
  19.                             var preloadimage=new Image()
  20.                             preloadimage.src=this.src
  21.                     })
  22.             },
  23.      
  24.             expandone:function(headerclass, selected){ //PUBLIC function to expand a particular header
  25.                     this.toggleone(headerclass, selected, "expand")
  26.             },
  27.      
  28.             collapseone:function(headerclass, selected){ //PUBLIC function to collapse a particular header
  29.                     this.toggleone(headerclass, selected, "collapse")
  30.             },
  31.      
  32.             expandall:function(headerclass){ //PUBLIC function to expand all headers based on their shared CSS classname
  33.                     var $headers=this.headergroup[headerclass]
  34.                     this.contentgroup[headerclass].filter(':hidden').each(function(){
  35.                             $headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
  36.                     })
  37.             },
  38.      
  39.             collapseall:function(headerclass){ //PUBLIC function to collapse all headers based on their shared CSS classname
  40.                     var $headers=this.headergroup[headerclass]
  41.                     this.contentgroup[headerclass].filter(':visible').each(function(){
  42.                             $headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
  43.                     })
  44.             },
  45.      
  46.             toggleone:function(headerclass, selected, optstate){ //PUBLIC function to expand/ collapse a particular header
  47.                     var $targetHeader=this.headergroup[headerclass].eq(selected)
  48.                     var $subcontent=this.contentgroup[headerclass].eq(selected)
  49.                     if (typeof optstate=="undefined" || optstate=="expand" && $subcontent.is(":hidden") || optstate=="collapse" && $subcontent.is(":visible"))
  50.                             $targetHeader.trigger("evt_accordion")
  51.             },
  52.      
  53.             ajaxloadcontent:function($targetHeader, $targetContent, config, callback){
  54.                     var ajaxinfo=$targetHeader.data('ajaxinfo')
  55.      
  56.                     function handlecontent(content){ //nested function
  57.                             if (content){ //if ajax content has loaded
  58.                                     ajaxinfo.cacheddata=content //remember ajax content
  59.                                     ajaxinfo.status="cached" //set ajax status to cached
  60.                                     if ($targetContent.queue("fx").length==0){ //if this content isn't currently expanding or collapsing
  61.                                             $targetContent.hide().html(content) //hide loading message, then set sub content's HTML to ajax content
  62.                                             ajaxinfo.status="complete" //set ajax status to complete
  63.                                             callback() //execute callback function- expand this sub content
  64.                                     }
  65.                             }
  66.                             if (ajaxinfo.status!="complete"){
  67.                                     setTimeout(function(){handlecontent(ajaxinfo.cacheddata)}, 100) //call handlecontent() again until ajax content has loaded (ajaxinfo.cacheddata contains data)
  68.                             }
  69.                     } //end nested function
  70.      
  71.                     if (ajaxinfo.status=="none"){ //ajax data hasn't been fetched yet
  72.                             $targetContent.html(this.ajaxloadingmsg)
  73.                             $targetContent.slideDown(config.animatespeed)
  74.                             ajaxinfo.status="loading" //set ajax status to "loading"
  75.                             $.ajax({
  76.                                     url: ajaxinfo.url, //path to external menu file
  77.                                     error:function(ajaxrequest){
  78.                                             handlecontent('Error fetching content. Server Response: '+ajaxrequest.responseText)
  79.                                     },
  80.                                     success:function(content){
  81.                                             content=(content=="")? " " : content //if returned content is empty, set it to "space" is content no longer returns false/empty (hasn't loaded yet)
  82.                                             handlecontent(content)
  83.                                     }
  84.                             })
  85.                     }
  86.                     else if (ajaxinfo.status=="loading")
  87.                             handlecontent(ajaxinfo.cacheddata)
  88.             },
  89.      
  90.             expandit:function($targetHeader, $targetContent, config, useractivated, directclick, skipanimation){
  91.                     var ajaxinfo=$targetHeader.data('ajaxinfo')
  92.                     if (ajaxinfo){ //if this content should be fetched via Ajax
  93.                             if (ajaxinfo.status=="none" || ajaxinfo.status=="loading")
  94.                                     this.ajaxloadcontent($targetHeader, $targetContent, config, function(){ddaccordion.expandit($targetHeader, $targetContent, config, useractivated, directclick)})
  95.                             else if (ajaxinfo.status=="cached"){
  96.                                     $targetContent.html(ajaxinfo.cacheddata)
  97.                                     ajaxinfo.cacheddata=null
  98.                                     ajaxinfo.status="complete"
  99.                             }
  100.                     }
  101.                     this.transformHeader($targetHeader, config, "expand")
  102.                     $targetContent.slideDown(skipanimation? 0 : config.animatespeed, function(){
  103.                             config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), useractivated)
  104.                             if (config.postreveal=="gotourl" && directclick){ //if revealtype is "Go to Header URL upon click", and this is a direct click on the header
  105.                                     var targetLink=($targetHeader.is("a"))? $targetHeader.get(0) : $targetHeader.find('a:eq(0)').get(0)
  106.                                     if (targetLink) //if this header is a link
  107.                                             setTimeout(function(){location=targetLink.href}, 200) //ignore link target, as window.open(targetLink, targetLink.target) doesn't work in FF if popup blocker enabled
  108.                             }
  109.                     })
  110.             },
  111.      
  112.             collapseit:function($targetHeader, $targetContent, config, isuseractivated){
  113.                     this.transformHeader($targetHeader, config, "collapse")
  114.                     $targetContent.slideUp(config.animatespeed, function(){config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), isuseractivated)})
  115.             },
  116.      
  117.             transformHeader:function($targetHeader, config, state){
  118.                     $targetHeader.addClass((state=="expand")? config.cssclass.expand : config.cssclass.collapse) //alternate btw "expand" and "collapse" CSS classes
  119.                     .removeClass((state=="expand")? config.cssclass.collapse : config.cssclass.expand)
  120.                     if (config.htmlsetting.location=='src'){ //Change header image (assuming header is an image)?
  121.                             $targetHeader=($targetHeader.is("img"))? $targetHeader : $targetHeader.find('img').eq(0) //Set target to either header itself, or first image within header
  122.                             $targetHeader.attr('src', (state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse) //change header image
  123.                     }
  124.                     else if (config.htmlsetting.location=="prefix") //if change "prefix" HTML, locate dynamically added ".accordprefix" span tag and change it
  125.                             $targetHeader.find('.accordprefix').html((state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse)
  126.                     else if (config.htmlsetting.location=="suffix")
  127.                             $targetHeader.find('.accordsuffix').html((state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse)
  128.             },
  129.      
  130.             urlparamselect:function(headerclass){
  131.                     var result=window.location.search.match(new RegExp(headerclass+"=((\\d+)(,(\\d+))*)", "i")) //check for "?headerclass=2,3,4" in URL
  132.                     if (result!=null)
  133.                             result=RegExp.$1.split(',')
  134.                     return result //returns null, [index], or [index1,index2,etc], where index are the desired selected header indices
  135.             },
  136.      
  137.             getCookie:function(Name){
  138.                     var re=new RegExp(Name+"=[^;]+", "i") //construct RE to search for target name/value pair
  139.                     if (document.cookie.match(re)) //if cookie found
  140.                             return document.cookie.match(re)[0].split("=")[1] //return its value
  141.                     return null
  142.             },
  143.      
  144.             setCookie:function(name, value){
  145.                     document.cookie = name + "=" + value + "; path=/"
  146.             },
  147.      
  148.             init:function(config){
  149.             document.write('<style type="text/css">\n')
  150.             document.write('.'+config.contentclass+'{display: none}\n') //generate CSS to hide contents
  151.             document.write('a.hiddenajaxlink{display: none}\n') //CSS class to hide ajax link
  152.             document.write('<\/style>')
  153.             jQuery(document).ready(function($){
  154.                     ddaccordion.urlparamselect(config.headerclass)
  155.                     var persistedheaders=ddaccordion.getCookie(config.headerclass)
  156.                     ddaccordion.headergroup[config.headerclass]=$('.'+config.headerclass) //remember header group for this accordion
  157.                     ddaccordion.contentgroup[config.headerclass]=$('.'+config.contentclass) //remember content group for this accordion
  158.                     var $headers=ddaccordion.headergroup[config.headerclass]
  159.                     var $subcontents=ddaccordion.contentgroup[config.headerclass]
  160.                     config.cssclass={collapse: config.toggleclass[0], expand: config.toggleclass[1]} //store expand and contract CSS classes as object properties
  161.                     config.revealtype=config.revealtype || "click"
  162.                     config.revealtype=config.revealtype.replace(/mouseover/i, "mouseenter")
  163.                     if (config.revealtype=="clickgo"){
  164.                             config.postreveal="gotourl" //remember added action
  165.                             config.revealtype="click" //overwrite revealtype to "click" keyword
  166.                     }
  167.                     if (typeof config.togglehtml=="undefined")
  168.                             config.htmlsetting={location: "none"}
  169.                     else
  170.                             config.htmlsetting={location: config.togglehtml[0], collapse: config.togglehtml[1], expand: config.togglehtml[2]} //store HTML settings as object properties
  171.                     config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
  172.                     config.onopenclose=(typeof config.onopenclose=="undefined")? function(){} : config.onopenclose //attach custom "onopenclose" event handler
  173.                     var lastexpanded={} //object to hold reference to last expanded header and content (jquery objects)
  174.                     var expandedindices=ddaccordion.urlparamselect(config.headerclass) || ((config.persiststate && persistedheaders!=null)? persistedheaders : config.defaultexpanded)
  175.                     if (typeof expandedindices=='string') //test for string value (exception is config.defaultexpanded, which is an array)
  176.                             expandedindices=expandedindices.replace(/c/ig, '').split(',') //transform string value to an array (ie: "c1,c2,c3" becomes [1,2,3]
  177.                     if (expandedindices.length==1 && expandedindices[0]=="-1") //check for expandedindices value of [-1], indicating persistence is on and no content expanded
  178.                             expandedindices=[]
  179.                     if (config["collapseprev"] && expandedindices.length>1) //only allow one content open?
  180.                             expandedindices=[expandedindices.pop()] //return last array element as an array (for sake of jQuery.inArray())
  181.                     if (config["onemustopen"] && expandedindices.length==0) //if at least one content should be open at all times and none are, open 1st header
  182.                             expandedindices=[0]
  183.                     $headers.each(function(index){ //loop through all headers
  184.                             var $header=$(this)
  185.                             if (/(prefix)|(suffix)/i.test(config.htmlsetting.location) && $header.html()!=""){ //add a SPAN element to header depending on user setting and if header is a container tag
  186.                                     $('<span class="accordprefix"></span>').prependTo(this)
  187.                                     $('<span class="accordsuffix"></span>').appendTo(this)
  188.                             }
  189.                             $header.attr('headerindex', index+'h') //store position of this header relative to its peers
  190.                             $subcontents.eq(index).attr('contentindex', index+'c') //store position of this content relative to its peers
  191.                             var $subcontent=$subcontents.eq(index)
  192.                             var $hiddenajaxlink=$subcontent.find('a.hiddenajaxlink:eq(0)') //see if this content should be loaded via ajax
  193.                             if ($hiddenajaxlink.length==1){
  194.                                     $header.data('ajaxinfo', {url:$hiddenajaxlink.attr('href'), cacheddata:null, status:'none'}) //store info about this ajax content inside header
  195.                             }
  196.                             var needle=(typeof expandedindices[0]=="number")? index : index+'' //check for data type within expandedindices array- index should match that type
  197.                             if (jQuery.inArray(needle, expandedindices)!=-1){ //check for headers that should be expanded automatically (convert index to string first)
  198.                                     ddaccordion.expandit($header, $subcontent, config, false, false, !config.animatedefault) //3rd last param sets 'isuseractivated' parameter, 2nd last sets isdirectclick, last sets skipanimation param
  199.                                     lastexpanded={$header:$header, $content:$subcontent}
  200.                             }  //end check
  201.                             else{
  202.                                     $subcontent.hide()
  203.                                     config.onopenclose($header.get(0), parseInt($header.attr('headerindex')), $subcontent.css('display'), false) //Last Boolean value sets 'isuseractivated' parameter
  204.                                     ddaccordion.transformHeader($header, config, "collapse")
  205.                             }
  206.                     })
  207.                     $headers.bind("evt_accordion", function(e, isdirectclick){ //assign CUSTOM event handler that expands/ contacts a header
  208.                                     var $subcontent=$subcontents.eq(parseInt($(this).attr('headerindex'))) //get subcontent that should be expanded/collapsed
  209.                                     if ($subcontent.css('display')=="none"){
  210.                                             ddaccordion.expandit($(this), $subcontent, config, true, isdirectclick) //2nd last param sets 'isuseractivated' parameter
  211.                                             if (config["collapseprev"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){ //collapse previous content?
  212.                                                     ddaccordion.collapseit(lastexpanded.$header, lastexpanded.$content, config, true) //Last Boolean value sets 'isuseractivated' parameter
  213.                                             }
  214.                                             lastexpanded={$header:$(this), $content:$subcontent}
  215.                                     }
  216.                                     else if (!config["onemustopen"] || config["onemustopen"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){
  217.                                             ddaccordion.collapseit($(this), $subcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
  218.                                     }
  219.                     })
  220.                     $headers.bind(config.revealtype, function(){
  221.                             if (config.revealtype=="mouseenter"){
  222.                                     clearTimeout(config.revealdelay)
  223.                                     var headerindex=parseInt($(this).attr("headerindex"))
  224.                                     config.revealdelay=setTimeout(function(){ddaccordion.expandone(config["headerclass"], headerindex)}, config.mouseoverdelay || 0)
  225.                             }
  226.                             else{
  227.                                     $(this).trigger("evt_accordion", [true])
  228.                                     //last parameter indicates this is a direct click on the header
  229.  
  230.                                     target=$(this).find("a");
  231.                                     console.log('false=' + $(target).attr('href'));
  232.                                     if($(target).attr('href'))
  233.                                     {
  234.                                             console.log('goto');
  235.                                             url=$(target).attr('href');
  236.                                             window.location = url;
  237.                                     }
  238.  
  239.                                     return false //cancel default click behavior
  240.                             }
  241.                     })
  242.                     $headers.bind("mouseleave", function(){
  243.                             clearTimeout(config.revealdelay)
  244.                     })
  245.                     config.oninit($headers.get(), expandedindices)
  246.                     $(window).bind('unload', function(){ //clean up and persist on page unload
  247.                             $headers.unbind()
  248.                             var expandedindices=[]
  249.                             $subcontents.filter(':visible').each(function(index){ //get indices of expanded headers
  250.                                     expandedindices.push($(this).attr('contentindex'))
  251.                             })
  252.                             if (config.persiststate==true && $headers.length>0){ //persist state?
  253.                                     expandedindices=(expandedindices.length==0)? '-1c' : expandedindices //No contents expanded, indicate that with dummy '-1c' value?
  254.                                     ddaccordion.setCookie(config.headerclass, expandedindices)
  255.                             }
  256.                     })
  257.             })
  258.             }
  259.     }
  260.      
  261.     //preload any images defined inside ajaxloadingmsg variable
  262.     ddaccordion.preloadimages(jQuery(ddaccordion.ajaxloadingmsg).filter('img'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement