Search code examples
javascriptjqueryif-statementresizevisible

jQuery - change element height if other element becomes visible


I have 3 buttons that toggleFade() 3 divs. When i click #link1, the div1 fadeIn() and so on.. My goal is to resize #map_canvas if any of these divs are faded in, and resize to default if none are visible (fadeOut()).

    <a id="link1"></a>
    <a id="link2"></a>
    <a id="link3"></a>

    <div id="map_canvas"></div>

    <div id="wrapper">

   <div id="div1" class="hideMe"></div>
   <div id="div2" class="hideMe"></div>
   <div id="div3" class="hideMe"></div>

   </div>

EDIT: jQuery of fadeIn and fadeOut.

 $(document).ready(function() {

     $('#div1').hide();
     $('a#link1').click(function() {

 if (!$('#div1').is(':visible')) 
   {
     $('.hideMe').fadeOut("slow");
     $('#map_canvas').animate({height:"370px"}, 500);
    }

     $('#div1').fadeToggle("slow");

  });

Solution

  • Well as much as I could understand I implemented an example. I only did the first two buttons you can use the first two buttons as example to implement the third.

    Note: Its possible to consolidate the jQuery so that there is only one click function however while learning Its helpful to keep it separated so its more understandable.

    HTML

    <a id="link1">link1</a>
    <a id="link2">link2</a>
    <a id="link3">link3</a>
    
    <div id="map_canvas"></div>
    
    <div id="wrapper">
    
    <div id="div1" class="hideMe">div1</div>
    <div id="div2" class="hideMe">div2</div>
    <div id="div3" class="hideMe">div3</div>
    

    Javascript/Jquery

    $(document).ready(function() {
            $('.hideMe').hide();
            $('#link1').click(function() {
              $('.hideMe').not('#div1').hide();
              $('#div1').fadeToggle("slow",function(){
                  if ($('#div1').is(':visible')) 
                  { 
                      $('#map_canvas').animate({height:"370px"}, 500);
                  }
                  if(!$('.hideMe').is(':visible')){
                      $('#map_canvas').animate({height:"0px"}, 500);
                  }
              });
            });
            $('#link2').click(function() {
                $('.hideMe').not('#div2').hide();
                $('#div2').fadeToggle("slow",function(){
                  if ($('#div2').is(':visible')) 
                      {
                        $('#map_canvas').animate({height:"370px"}, 500);
                      }
                  if(!$('.hideMe').is(':visible')){
                      $('#map_canvas').animate({height:"0px"}, 500);
                  }
                });
              });
        });
    

    CSS

           #map_canvas {
            border: 1px solid black;
           }
           a {
               cursor:pointer;
           }
    

    Fiddle can be found here

    http://jsfiddle.net/qYys7/