JAVASCRIPT   28

animatedcollapse

Guest on 20th August 2022 12:44:16 AM

  1. //** Animated Collapsible DIV v2.0- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com.
  2. //** May 24th, 08'- Script rewritten and updated to 2.0.
  3. //** June 4th, 08'- Version 2.01: Bug fix to work with jquery 1.2.6 (which changed the way attr() behaves).
  4. //** March 5th, 09'- Version 2.2, which adds the following:
  5.                         //1) ontoggle($, divobj, state) event that fires each time a DIV is expanded/collapsed, including when the page 1st loads
  6.                         //2) Ability to expand a DIV via a URL parameter string, ie: index.htm?expanddiv=jason or index.htm?expanddiv=jason,kelly
  7.  
  8. //** March 9th, 09'- Version 2.2.1: Optimized ontoggle event handler slightly.
  9. //** July 3rd, 09'- Version 2.4, which adds the following:
  10.                         //1) You can now insert rel="expand[divid] | collapse[divid] | toggle[divid]" inside arbitrary links to act as DIV togglers
  11.                         //2) For image toggler links, you can insert the attributes "data-openimage" and "data-closedimage" to update its image based on the DIV state
  12.  
  13. var animatedcollapse={
  14. divholders: {}, //structure: {div.id, div.attrs, div.$divref, div.$togglerimage}
  15. divgroups: {}, //structure: {groupname.count, groupname.lastactivedivid}
  16. lastactiveingroup: {}, //structure: {lastactivediv.id}
  17. preloadimages: [],
  18.  
  19. show:function(divids){ //public method
  20.         if (typeof divids=="object"){
  21.                 for (var i=0; i<divids.length; i++)
  22.                         this.showhide(divids[i], "show")
  23.         }
  24.         else
  25.                 this.showhide(divids, "show")
  26. },
  27.  
  28. hide:function(divids){ //public method
  29.         if (typeof divids=="object"){
  30.                 for (var i=0; i<divids.length; i++)
  31.                         this.showhide(divids[i], "hide")
  32.         }
  33.         else
  34.                 this.showhide(divids, "hide")
  35. },
  36.  
  37. toggle:function(divid){ //public method
  38.         if (typeof divid=="object")
  39.                 divid=divid[0]
  40.         this.showhide(divid, "toggle")
  41. },
  42.  
  43. addDiv:function(divid, attrstring){ //public function
  44.         this.divholders[divid]=({id: divid, $divref: null, attrs: attrstring})
  45.         this.divholders[divid].getAttr=function(name){ //assign getAttr() function to each divholder object
  46.                 var attr=new RegExp(name+"=([^,]+)", "i") //get name/value config pair (ie: width=400px,)
  47.                 return (attr.test(this.attrs) && parseInt(RegExp.$1)!=0)? RegExp.$1 : null //return value portion (string), or 0 (false) if none found
  48.         }
  49.         this.currentid=divid //keep track of current div object being manipulated (in the event of chaining)
  50.         return this
  51. },
  52.  
  53. showhide:function(divid, action){
  54.         var $divref=this.divholders[divid].$divref //reference collapsible DIV
  55.         if (this.divholders[divid] && $divref.length==1){ //if DIV exists
  56.                 var targetgroup=this.divgroups[$divref.attr('groupname')] //find out which group DIV belongs to (if any)
  57.                 if ($divref.attr('groupname') && targetgroup.count>1 && (action=="show" || action=="toggle" && $divref.css('display')=='none')){ //If current DIV belongs to a group
  58.                         if (targetgroup.lastactivedivid && targetgroup.lastactivedivid!=divid) //if last active DIV is set
  59.                                 this.slideengine(targetgroup.lastactivedivid, 'hide') //hide last active DIV within group first
  60.                                 this.slideengine(divid, 'show')
  61.                         targetgroup.lastactivedivid=divid //remember last active DIV
  62.                 }
  63.                 else{
  64.                         this.slideengine(divid, action)
  65.                 }
  66.         }
  67. },
  68.  
  69. slideengine:function(divid, action){
  70.         var $divref=this.divholders[divid].$divref
  71.         var $togglerimage=this.divholders[divid].$togglerimage
  72.         if (this.divholders[divid] && $divref.length==1){ //if this DIV exists
  73.                 var animateSetting={height: action}
  74.                 if ($divref.attr('fade'))
  75.                         animateSetting.opacity=action
  76.                 $divref.animate(animateSetting, $divref.attr('speed')? parseInt($divref.attr('speed')) : 500, function(){
  77.                         if ($togglerimage){
  78.                                 $togglerimage.attr('src', ($divref.css('display')=="none")? $togglerimage.data('srcs').closed : $togglerimage.data('srcs').open)
  79.                         }
  80.                         if (animatedcollapse.ontoggle){
  81.                                 try{
  82.                                         animatedcollapse.ontoggle(jQuery, $divref.get(0), $divref.css('display'))
  83.                                 }
  84.                                 catch(e){
  85.                                         alert("An error exists inside your \"ontoggle\" function:\n\n"+e+"\n\nAborting execution of function.")
  86.                                 }
  87.                         }
  88.                 })
  89.                 return false
  90.         }
  91. },
  92.  
  93. generatemap:function(){
  94.         var map={}
  95.         for (var i=0; i<arguments.length; i++){
  96.                 if (arguments[i][1]!=null){ //do not generate name/value pair if value is null
  97.                         map[arguments[i][0]]=arguments[i][1]
  98.                 }
  99.         }
  100.         return map
  101. },
  102.  
  103. init:function(){
  104.         var ac=this
  105.         jQuery(document).ready(function($){
  106.                 animatedcollapse.ontoggle=animatedcollapse.ontoggle || null
  107.                 var urlparamopenids=animatedcollapse.urlparamselect() //Get div ids that should be expanded based on the url (['div1','div2',etc])
  108.                 var persistopenids=ac.getCookie('acopendivids') //Get list of div ids that should be expanded due to persistence ('div1,div2,etc')
  109.                 var groupswithpersist=ac.getCookie('acgroupswithpersist') //Get list of group names that have 1 or more divs with "persist" attribute defined
  110.                 if (persistopenids!=null) //if cookie isn't null (is null if first time page loads, and cookie hasnt been set yet)
  111.                         persistopenids=(persistopenids=='nada')? [] : persistopenids.split(',') //if no divs are persisted, set to empty array, else, array of div ids
  112.                 groupswithpersist=(groupswithpersist==null || groupswithpersist=='nada')? [] : groupswithpersist.split(',') //Get list of groups with divs that are persisted
  113.                 jQuery.each(ac.divholders, function(){ //loop through each collapsible DIV object
  114.                         this.$divref=$('#'+this.id)
  115.                         if ((this.getAttr('persist') || jQuery.inArray(this.getAttr('group'), groupswithpersist)!=-1) && persistopenids!=null){ //if this div carries a user "persist" setting, or belong to a group with at least one div that does
  116.                                 var cssdisplay=(jQuery.inArray(this.id, persistopenids)!=-1)? 'block' : 'none'
  117.                         }
  118.                         else{
  119.                                 var cssdisplay=this.getAttr('hide')? 'none' : null
  120.                         }
  121.                         if (urlparamopenids[0]=="all" || jQuery.inArray(this.id, urlparamopenids)!=-1){ //if url parameter string contains the single array element "all", or this div's ID
  122.                                 cssdisplay='block' //set div to "block", overriding any other setting
  123.                         }
  124.                         else if (urlparamopenids[0]=="none"){
  125.                                 cssdisplay='none' //set div to "none", overriding any other setting
  126.                         }
  127.                         this.$divref.css(ac.generatemap(['height', this.getAttr('height')], ['display', cssdisplay]))
  128.                         this.$divref.attr(ac.generatemap(['groupname', this.getAttr('group')], ['fade', this.getAttr('fade')], ['speed', this.getAttr('speed')]))
  129.                         if (this.getAttr('group')){ //if this DIV has the "group" attr defined
  130.                                 var targetgroup=ac.divgroups[this.getAttr('group')] || (ac.divgroups[this.getAttr('group')]={}) //Get settings for this group, or if it no settings exist yet, create blank object to store them in
  131.                                 targetgroup.count=(targetgroup.count||0)+1 //count # of DIVs within this group
  132.                                 if (jQuery.inArray(this.id, urlparamopenids)!=-1){ //if url parameter string contains this div's ID
  133.                                         targetgroup.lastactivedivid=this.id //remember this DIV as the last "active" DIV (this DIV will be expanded). Overrides other settings
  134.                                         targetgroup.overridepersist=1 //Indicate to override persisted div that would have been expanded
  135.                                 }
  136.                                 if (!targetgroup.lastactivedivid && this.$divref.css('display')!='none' || cssdisplay=="block" && typeof targetgroup.overridepersist=="undefined") //if this DIV was open by default or should be open due to persistence                                                              
  137.                                         targetgroup.lastactivedivid=this.id //remember this DIV as the last "active" DIV (this DIV will be expanded)
  138.                                 this.$divref.css({display:'none'}) //hide any DIV that's part of said group for now
  139.                         }
  140.                 }) //end divholders.each
  141.                 jQuery.each(ac.divgroups, function(){ //loop through each group
  142.                         if (this.lastactivedivid && urlparamopenids[0]!="none") //show last "active" DIV within each group (one that should be expanded), unless url param="none"
  143.                                 ac.divholders[this.lastactivedivid].$divref.show()
  144.                 })
  145.                 if (animatedcollapse.ontoggle){
  146.                         jQuery.each(ac.divholders, function(){ //loop through each collapsible DIV object and fire ontoggle event
  147.                                 animatedcollapse.ontoggle(jQuery, this.$divref.get(0), this.$divref.css('display'))
  148.                         })
  149.                 }
  150.                 //Parse page for links containing rel attribute
  151.                 var $allcontrols=$('a[rel]').filter('[rel^="collapse["], [rel^="expand["], [rel^="toggle["]') //get all elements on page with rel="collapse[]", "expand[]" and "toggle[]"
  152.                 $allcontrols.each(function(){ //loop though each control link
  153.                         this._divids=this.getAttribute('rel').replace(/(^\w+)|(\s+)/g, "").replace(/[\[\]']/g, "") //cache value 'div1,div2,etc' within identifier[div1,div2,etc]
  154.                         if (this.getElementsByTagName('img').length==1 && ac.divholders[this._divids]){ //if control is an image link that toggles a single DIV (must be one to one to update status image)
  155.                                 animatedcollapse.preloadimage(this.getAttribute('data-openimage'), this.getAttribute('data-closedimage')) //preload control images (if defined)
  156.                                 $togglerimage=$(this).find('img').eq(0).data('srcs', {open:this.getAttribute('data-openimage'), closed:this.getAttribute('data-closedimage')}) //remember open and closed images' paths
  157.                                 ac.divholders[this._divids].$togglerimage=$(this).find('img').eq(0) //save reference to toggler image (to be updated inside slideengine()
  158.                                 ac.divholders[this._divids].$togglerimage.attr('src', (ac.divholders[this._divids].$divref.css('display')=="none")? $togglerimage.data('srcs').closed : $togglerimage.data('srcs').open)
  159.                         }
  160.                         $(this).click(function(){ //assign click behavior to each control link
  161.                                 var relattr=this.getAttribute('rel')
  162.                                 var divids=(this._divids=="")? [] : this._divids.split(',') //convert 'div1,div2,etc' to array
  163.                                 if (divids.length>0){
  164.                                         animatedcollapse[/expand/i.test(relattr)? 'show' : /collapse/i.test(relattr)? 'hide' : 'toggle'](divids) //call corresponding public function
  165.                                         return false
  166.                                 }
  167.                         }) //end control.click
  168.                 })// end control.each
  169.  
  170.                 $(window).bind('unload', function(){
  171.                         ac.uninit()
  172.                 })
  173.         }) //end doc.ready()
  174. },
  175.  
  176. uninit:function(){
  177.         var opendivids='', groupswithpersist=''
  178.         jQuery.each(this.divholders, function(){
  179.                 if (this.$divref.css('display')!='none'){
  180.                         opendivids+=this.id+',' //store ids of DIVs that are expanded when page unloads: 'div1,div2,etc'
  181.                 }
  182.                 if (this.getAttr('group') && this.getAttr('persist'))
  183.                         groupswithpersist+=this.getAttr('group')+',' //store groups with which at least one DIV has persistance enabled: 'group1,group2,etc'
  184.         })
  185.         opendivids=(opendivids=='')? 'nada' : opendivids.replace(/,$/, '')
  186.         groupswithpersist=(groupswithpersist=='')? 'nada' : groupswithpersist.replace(/,$/, '')
  187.         this.setCookie('acopendivids', opendivids)
  188.         this.setCookie('acgroupswithpersist', groupswithpersist)
  189. },
  190.  
  191. getCookie:function(Name){
  192.         var re=new RegExp(Name+"=[^;]*", "i"); //construct RE to search for target name/value pair
  193.         if (document.cookie.match(re)) //if cookie found
  194.                 return document.cookie.match(re)[0].split("=")[1] //return its value
  195.         return null
  196. },
  197.  
  198. setCookie:function(name, value, days){
  199.         if (typeof days!="undefined"){ //if set persistent cookie
  200.                 var expireDate = new Date()
  201.                 expireDate.setDate(expireDate.getDate()+days)
  202.                 document.cookie = name+"="+value+"; path=/; expires="+expireDate.toGMTString()
  203.         }
  204.         else //else if this is a session only cookie
  205.                 document.cookie = name+"="+value+"; path=/"
  206. },
  207.  
  208. urlparamselect:function(){
  209.         window.location.search.match(/expanddiv=([\w\-_,]+)/i) //search for expanddiv=divid or divid1,divid2,etc
  210.         return (RegExp.$1!="")? RegExp.$1.split(",") : []
  211. },
  212.  
  213. preloadimage:function(){
  214.         var preloadimages=this.preloadimages
  215.         for (var i=0; i<arguments.length; i++){
  216.                 if (arguments[i] && arguments[i].length>0){
  217.                         preloadimages[preloadimages.length]=new Image()
  218.                         preloadimages[preloadimages.length-1].src=arguments[i]
  219.                 }
  220.         }
  221. }
  222.  
  223. }

Raw Paste


Login or Register to edit or fork this paste. It's free.