jQuery: sliding forms

My good friend Carlo asked me a question: "I have two forms on a page. I want these forms to be first hidden and then shown with a sliding effect when you click on two links which point to the corresponding forms. I want only one form to be shown per time. How can I do this with jQuery?". Let's see how.

First, we need to hide both forms. Then we add a click handler on each link. Inside each handler function, we should show only the corresponding form where the link points to. Further, we also have to check if the other form is visible or not. If so, we hide it:

$(function() {

  $('form').hide();
  
  $('#f1').click(function(event) {
  
  
    $('#form1').slideDown();
    
    if($('#form2').is(':visible')) {
      $('#form2').slideUp();
    }
  
    event.preventDefault();
  
  });
  
  $('#f2').click(function(event) {
  
  
    $('#form2').slideDown();
    
    if($('#form1').is(':visible')) {
    
      $('#form1').slideUp();
      
    }
  
    event.preventDefault();
  
  });


});

We use the is() method to check if the other form is visible. If so, we hide it. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “jQuery: sliding forms”

Leave a Reply

Note: Only a member of this blog may post a comment.