views:

389

answers:

2

I am working with JQuery and I'm trying to change the html of a div box when the child div slides in and out. My problem is that the code below isn't changing the html value of #menu_text. It only displays Hide Menu and is not detecting the real height as changed by slideToggle.

 $('#menu').click(function () {
  $('#menu_links').slideToggle('slow', function(){

   console.log('Debug : %s', $('#menu_links').height());

   if ($('#menu_links').height() == 1)
    $('#menu_text').html("Show Menu");
   else if ($('#menu_links').height() == 20)
    $('#menu_text').html("Hide Menu");

  });
 });

Upon inspection in firebug console, The value of height never changes from 20 unless you click the div really fast multiple times then it will change to 1. (I should add that the height defined in the style sheet is 20)

The doc says that slideToggle only affects the height of the object. Am I missing something? Thank you for the help.

    <div id="menu"><p id="menu_text">Show Menu</p>
     <div id="menu_links">
            Stuff
   </div>
 </div>
+1  A: 

Try:

$('#menu').click(function(){
    $('#menu_links').slideToggle('slow', function(){
        $('#menu_text').html($('#menu_links:visible').length ? "Hide menu" : "Show menu");
    });
});

There you'll set the text of the menu depending on if the links element is visible or not. You're probably better off not depending on element's heights and widths, as in the worst case they might vary from browser to browser (and in this case, they'll also change according to the content of the links element).

antti_s
Thank you. I didn't realize there was a visible selector for the jquery action. Learn something new every day.
Maarek
A: 

You could also use data() to save your state. It's a great trick to save state or anything

$('#menu').click(function () {
  $('#menu_links').slideToggle('slow', function(){

   var $this = $(this);
   var toggled = $this.data('toggled');
   if (toggled)
    $('#menu_text').html("Show Menu");
   else 
    $('#menu_text').html("Hide Menu");
   $this.data('toggled', !toggled)

  });
 });
Ben
Thanks, I should have detected some sort of state change instead of the actual values of what it could be.
Maarek