Advertisement
GWibisono

ddacordian.js

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