aknosis.com

webdev && sysadmin quips, tips, articles + more

Fun With jQuery - Toggle() - Easy Tips to Visually Enhance Your Website

| Comments

Here’s a quick tip to add some cool effects with jQuery that require very little code to implement. In this example I’m going to so how use of the toggle function can make the simplest functionality and jazz it up.

.toggle()

In a nutshell, the toggle function will call the show() function if your element isn’t visible and the hide() function if it is.

  • Hamburger
  • Philly Cheese Steak
  • Taco
  • Pizza
  • Something else greasy and unhealthy
1
<input onclick="$('#preview1').toggle();" type="button" value="Toggle My Menu" />

So as expected, clicking the button will toggle the menu. Now lets get a little more flashy:

  • Hamburger
  • Philly Cheese Steak
  • Taco
  • Pizza
  • Something else greasy and unhealthy
1
<input onclick="$('#preview2').toggle('slow');" type="button" value="Toggle My Menu" />

Now you have a ‘sliding’ type effect for showing and hiding contents all with about 40 extra characters of text. Want to be a bit more ‘dynamic’?

  • Hamburger
  • Philly Cheese Steak
  • Taco
  • Pizza
  • Something else greasy and unhealthy
1
<input class="button" id="menuToggler" onclick="$('#preview3').toggle('slow',function(){if($(this).is(':visible')){$('#menuToggler').val('Hide My Menu');}else{$('#menuToggler').val('Show My Menu');}});" type="button" value="Hide My Menu" />

Here is better formatted javascript:

1
2
3
4
5
6
7
8
9
$('#preview3').toggle('slow',
  function(){
      if($(this).is(':visible')){
          $('#menuToggler').val('Hide My Menu');
      }else{
          $('#menuToggler').val('Show My Menu');
      }
  }
);

What happens here is I have now created a function that is called once the toggle animation is done, it checks to see if the menu is visible and changes the buttons value based on that check.

As I said before, toggle just does the math and executes a hide or show on the element. Here is an example of the same thing using hide and show seperately.

  • Hamburger
  • Philly Cheese Steak
  • Taco
  • Pizza
  • Something else greasy and unhealthy
1
2
<input class="button" onclick="$('#preview4').hide('slow');" type="button" value="Hide My Menu" />
<input class="button" onclick="$('#preview4').show('slow');" type="button" value="Show My Menu" />

Stay tuned for more fun with jQuery, my favorite JavaScript library. http://jquery.com/

Comments