Click here to Skip to main content
15,915,842 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In a page, there are multiple Expand/Collapse parts. Each of them is structured like that below:
JavaScript
<h3 class="expand">Part I</h3>
<div class="collapse">
   <p>Text in Part I</p>
   <p>Text in Part I</p>
</div>
The related JS code is below. What I want is that when clicking to expand one part, other parts should be collapsed. How can this function be added to modify the existing code? Thanks.
JavaScript
$(function () {
    $("h3.expand").toggler({
        initShow: "div.collapse:first"
    });
    $("#content").expandAll({ trigger: "h3.expand", ref: "div.demo", speed: 300, oneSwitch: false });
});

<pre lang="Javascript">
/*! 
 * expandAll v.1.3.8.3
 * http://www.adipalaz.com/experiments/jquery/expand.html
 *
 * Requires: jQuery v. 1.3+ / updated for jQuery v. 1.9 /
 * Copyright (c) 2009, 2010, 2011, 2012, 2013 Adriana Palazova
 *
 * Dual licensed under the MIT (http://www.adipalaz.com/docs/mit-license.txt) and GPL v. 2 (http://www.adipalaz.com/docs/gpl-license.txt) licenses
 */
;(function($) {
//"use strict";
$.fn.expandAll = function(options) {

    var version = '1.3.8.3';
    var o = $.extend({}, $.fn.expandAll.defaults, options);   
    
    return this.each(function(index) {
        var $$ = $(this), $referent, $sw, $cllps, $tr, container, toggleTxt, toggleClass;
               
        // --- functions:
       (o.switchPosition == 'before') ? ($.fn.findSibling = $.fn.prev, $.fn.insrt = $.fn.before) : ($.fn.findSibling = $.fn.next, $.fn.insrt = $.fn.after);
                    
        // --- var container 
        if (this.id.length) { container = '#' + this.id;
        } else if (this.className.length) { container = this.tagName.toLowerCase() + '.' + this.className.split(' ').join('.');
        } else { container = this.tagName.toLowerCase();}
        
        // --- var $referent
        if (o.ref && $$.find(o.ref).length) {
          (o.switchPosition == 'before') ? $referent = $$.find(o.ref).filter(':first') : $referent = $$.find(o.ref).filter(':last');
        } else { return; }
        
        // end the script if the length of the collapsible element isn't long enough.  
        if (o.cllpsLength && $$.closest(container).find(o.cllpsEl).text().length < o.cllpsLength) {$$.closest(container).find(o.cllpsEl).addClass('dont_touch'); return;}
    
        // --- init state:
        (o.initTxt == 'show') ? (toggleTxt = o.expTxt, toggleClass='') : (toggleTxt = o.cllpsTxt, toggleClass='open');
        if (o.state == 'hidden') { 
          $$.find(o.cllpsEl + ':not(.shown, .dont_touch)').hide().findSibling().find('> a.open').removeClass('open').data('state', 0); 
        } else {
          $$.find(o.cllpsEl).show().findSibling().find('> a').addClass('open').data('state', 1); 
        }
        
        (o.oneSwitch) ? ($referent.insrt('<p class="switch"><a href="#" class="' + toggleClass + '">' + toggleTxt + '</a></p>')) :
          ($referent.insrt('<p class="switch"><a href="#" class="">' + o.expTxt + '</a> | <a href="#" class="open">' + o.cllpsTxt + '</a></p>'));

        // --- var $sw, $cllps, $tr :
        $sw = $referent.findSibling('p').find('a');
        $cllps = $$.closest(container).find(o.cllpsEl).not('.dont_touch');
        $tr = (o.trigger) ? $$.closest(container).find(o.trigger + ' > a') : $$.closest(container).find('.expand > a');
                
        if (o.child) {
          $$.find(o.cllpsEl + '.shown').show().findSibling().find('> a').addClass('open').text(o.cllpsTxt);
          window.$vrbls = { kt1 : o.expTxt, kt2 : o.cllpsTxt };
        }

        var scrollElem;
        (typeof scrollableElement == 'function') ? (scrollElem = scrollableElement('html', 'body')) : (scrollElem = 'html, body');
        
        $sw.click(function() {
            var $switch = $(this),
                $c = $switch.closest(container).find(o.cllpsEl).filter(':first'),
                cOffset = $c.offset().top - o.offset;
            if (o.parent) {
              var $swChildren = $switch.parent().nextAll().children('p.switch').find('a');
                  kidTxt1 = $vrbls.kt1, kidTxt2 = $vrbls.kt2,
                  kidTxt = ($switch.text() == o.expTxt) ? kidTxt2 : kidTxt1;
              $swChildren.text(kidTxt);
              if ($switch.text() == o.expTxt) {$swChildren.addClass('open');} else {$swChildren.removeClass('open');}
            }
            if ($switch.text() == o.expTxt) {
              if (o.oneSwitch) {$switch.text(o.cllpsTxt).attr('class', 'open');}
              $tr.addClass('open').data('state', 1);
              $cllps[o.showMethod](o.speed);
            } else {
              if (o.oneSwitch) {$switch.text(o.expTxt).attr('class', '');}
              $tr.removeClass('open').data('state', 0);
              if (o.speed == 0 || o.instantHide) {$cllps.hide();} else {$cllps[o.hideMethod](o.speed);}
              if (o.scroll && cOffset < $(window).scrollTop()) {$(scrollElem).animate({scrollTop: cOffset},600);}
          }
          return false;
        });
        /* -----------------------------------------------
        To save file size, feel free to remove the following code if you don't use the option: 'localLinks: true'
        -------------------------------------------------- */
        if (o.localLinks) { 
          var localLink = $(container).find(o.localLinks);
          if (localLink.length) {
            // based on http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links:
            $(localLink).click(function() {
              var $target = $(this.hash);
              $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
              if ($target.length) {
                var tOffset = $target.offset().top;
                $(scrollElem).animate({scrollTop: tOffset},600);
                return false;
              }
            });
          }
        }
        /* -----------------------------------------------
        Feel free to remove the following function if you don't use the options: 'localLinks: true' or 'scroll: true'
        -------------------------------------------------- */
        //http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links:
        function scrollableElement(els) {
          for (var i = 0, argLength = arguments.length; i < argLength; i++) {
            var el = arguments[i],
                $scrollElement = $(el);
            if ($scrollElement.scrollTop() > 0) {
              return el;
            } else {
              $scrollElement.scrollTop(1);
              var isScrollable = $scrollElement.scrollTop() > 0;
              $scrollElement.scrollTop(0);
              if (isScrollable) {
                return el;
              }
            }
          };
          return [];
        }; 
      /* --- end of the optional code --- */
});};
$.fn.expandAll.defaults = {
        state : 'hidden', // If 'hidden', the collapsible elements are hidden by default, else they are expanded by default 
        initTxt : 'show', // 'show' - if the initial text of the switch is for expanding, 'hide' - if the initial text of the switch is for collapsing
        expTxt : '[Expand All]', // the text of the switch for expanding
        cllpsTxt : '[Collapse All]', // the text of the switch for collapsing
        oneSwitch : true, // true or false - whether both [Expand All] and [Collapse All] are shown, or they swap
        ref : '.expand', // the switch 'Expand All/Collapse All' is inserted in regards to the element specified by 'ref'
        switchPosition: 'before', //'before' or 'after' - specifies the position of the switch 'Expand All/Collapse All' - before or after the collapsible element
        scroll : false, // false or true. If true, the switch 'Expand All/Collapse All' will be dinamically repositioned to remain in view when the collapsible element closes
        offset : 20,
        showMethod : 'slideDown', // 'show', 'slideDown', 'fadeIn', or custom
        hideMethod : 'slideUp', // 'hide', 'slideUp', 'fadeOut', or custom
        speed : 600, // the speed of the animation in m.s. or 'slow', 'normal', 'fast'
        cllpsEl : '.collapse', // the collapsible element
        trigger : '.expand', // if expandAll() is used in conjunction with toggle() - the elements that contain the trigger of the toggle effect on the individual collapsible sections
        localLinks : null, // null or the selector of the same-page links to which we will apply a smooth-scroll function, e.g. 'a.to_top'
        parent : false, // true, false
        child : false, // true, false
        cllpsLength : null, //null, {Number}. If {Number} (e.g. cllpsLength: 200) - if the number of characters inside the "collapsible element" is less than the given {Number}, the element will be visible all the time
        instantHide : false // {true} fixes hiding content inside hidden elements
};

/*! ---------------------------------------------
Toggler v.1.0
http://www.adipalaz.com/experiments/jquery/expand.html
Requires: jQuery v1.3+
Copyright (c) 2009 Adriana Palazova
Dual licensed under the MIT (http://www.adipalaz.com/docs/mit-license.txt) and GPL (http://www.adipalaz.com/docs/gpl-license.txt) licenses
------------------------------------------------ */
$.fn.toggler = function(options) {
    var o = $.extend({}, $.fn.toggler.defaults, options);
    
    var $this = $(this);
    $this.wrapInner('<a style="display:block" href="#" title="Expand/Collapse" />');
    if (o.initShow) {$(o.initShow).addClass('shown');}
    $this.next(o.cllpsEl + ':not(.shown)').hide();
    return this.each(function() {
      var container;
      (o.container) ? container = o.container : container = 'html';
      if ($this.next('div.shown').length) { $this.closest(container).find('.shown').show().prev().find('a').addClass('open'); }
      $(this).click(function() {
        $(this).find('a').toggleClass('open').end().next(o.cllpsEl)[o.method](o.speed);
        return false;
    });
});};
$.fn.toggler.defaults = {
     cllpsEl : 'div.collapse',
     method : 'slideToggle',
     speed : 'slow',
     container : '', //the common container of all groups with collapsible content (optional)
     initShow : '.shown' //the initially expanded sections (optional)
};
/* ---------------------------------------------
Feel free to remove any of the following functions if you don't need it.
------------------------------------------------ */

var msie = false;
if(typeof window.attachEvent != 'undefined') { msie = true; }

$.fn.fadeToggle = function(speed, callback) {
    return this.animate({opacity: 'toggle'}, speed, function() { 
    if (msie) { this.style.removeAttribute('filter'); }
    if (jQuery.isFunction(callback)) { callback(); }
  }); 
};
$.fn.slideFadeToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, function() { 
    if (msie) { this.style.removeAttribute('filter'); }
    if (jQuery.isFunction(callback)) { callback(); }
  }); 
};
$.fn.slideFadeDown = function(speed, callback) { 
  return this.animate({opacity: 'show', height: 'show'}, speed, function() { 
    if (msie) { this.style.removeAttribute('filter'); }
    if (jQuery.isFunction(callback)) { callback(); }
  }); 
}; 
$.fn.slideFadeUp = function(speed, callback) { 
  return this.animate({opacity: 'hide', height: 'hide'}, speed, function() { 
    if (msie) { this.style.removeAttribute('filter'); }
    if (jQuery.isFunction(callback)) { callback(); }
  }); 
}; 
/* --- end of the optional code --- */
})(jQuery);
Posted

As much i can understand is you want to expand one of several part expanded at one by clicking any of part(or any icon)

Here you can do this. Its very simple like
JavaScript
<script type="text/javascript">
   function ToggleParts(partToShow)
   {
      //hide all
      $( "input[id^='part']").hide();
      //show the clicked
      $( '#' + partToShow).show();
   }
</script>

HTML
<body>
<div id="part1"  önclick="ToggleParts('part1')"> Part1 : Any content </div>
<div id="part2"  önclick="ToggleParts('part2')"> Part2 : Any content </div>
<div id="part3"  önclick="ToggleParts('part3')"> Part3 : Any content </div>
<div id="part4"  önclick="ToggleParts('part4')"> Part4 : Any content </div>
</body>
 
Share this answer
 
v2
Comments
[no name] 21-Mar-14 14:17pm    
Puneet: Thank you for your code. I added your code, but the function ToggleParts(partToShow) is not called - I added a 'debugger;' line but the no stop there after I clicked an Expand/Collapse button. Did I still miss something?
What I did are below:
1) Added function ToggleParts(partToShow) in <script> section.
2) For each related <div>, code like you recommended
<div class="collapse" id="part1" önclick="ToggleParts('part1')">
Thanks.
[no name] 21-Mar-14 14:45pm    
Tried but the ToggleParts(partToShow) is not fired with a click on an Expand/Collapse button.
[no name] 21-Mar-14 15:01pm    
Dear Puneet: I also noticed a potential problem related to 'unicode' issue in your code. E.g., in yours önclick the ö is different from o. If using copy & paste, yours may not be recognized correctly. To avoid any possible unicode conflict, I re-typed every character. However, the ToggleParts() is still not fired.
Here is full working code. YOu have to include the Jquery LIbrary to use this.

XML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script type="text/javascript">
        function ToggleParts(partToShow) {
            //hide all
            //alert($('#' + partToShow).is(':visible'));
            if ($('#' + partToShow).is(':visible')) {
                $("[id^='part']").show();
                //show the clicked
                $('#' + partToShow).hide();
            }
            else {
                $("[id^='part']").hide();
                //show the clicked
                $('#' + partToShow).show();
            }
        }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 <input type="button" onclick="ToggleParts('part1')"  value="togglePart1"/>
 <input type="button" onclick="ToggleParts('part2')"  value="togglePart2"/>
 <input type="button" onclick="ToggleParts('part3')" value="togglePart3"/>
 <input type="button" onclick="ToggleParts('part4')"  value="togglePart4"/>
<div id="part1" > Part1 : Any content </div>


<div id="part2" style="display:none"> Part2 : Any content </div>


<div id="part3" style="display:none"> Part3 : Any content </div>

<div id="part4" style="display:none"> Part4 : Any content </div>

    </div>
    </form>
</body>
</html>
 
Share this answer
 
Comments
[no name] 24-Mar-14 8:08am    
Thanks for your 2nd solution. In my code, there is no HTML button controls. I am still to try find out why the ToggleParts() is not fired.
Ok as you have the following part
XML
<h3 class="expand">Part I</h3>
<div class="collapse">
   <p>Text in Part I</p>
   <p>Text in Part I</p>
</div>


So just add the 'onclick="ToggleParts('part1')"' event to 'h' html like this

<h3 class="expand" onclick="ToggleParts('part1')">Part 1</h3>

let the remaining code as per my 2nd solution.
 
Share this answer
 
Comments
[no name] 24-Mar-14 8:57am    
Still got the same result. The key is the ToggleParts() not fired at all. There must be something wrong in my code. I will check it again. Thanks.
[no name] 24-Mar-14 10:16am    
Dear Puneet: Per your comment "tough luck buddy. You can send me the exact code block you facing the issue in firing this even. I always there." Thanks SO much for your kindness. My email is syu@wmata.com. Please respond me an email and then I can send you the code. Thanks again.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900