tags:

views:

1675

answers:

1

Hi,

My code is working, but requiring me to click twice to active my chaining (once for the click event, and once for the toggle event.) What can I do to make it so I only have to click once so that the toggle will automatically occur?

    //Show or Hide Comments
$('#showHideComments').live('click', function() {
    $('#showHideComments').toggle(function() {
        $(".commentsSwitch").animate({"marginLeft": "+=53px"}, 500);
        $("#comments").fadeIn(300);
        $("#addComment").fadeIn(300);
    },function(){
        $(".commentsSwitch").animate({"marginLeft": "-=53px"}, 500);
        $("#comments").fadeOut(300);
        $("#addComment").fadeOut(300);
    });
});

Thanks!

+13  A: 

You cannot use live and toggle together. What you can do, is simply make your own "toggle" of sorts:

$('#showHideComments').live('click', function() {
    if($("#addComment").is(':visible')){
      $(".commentsSwitch").animate({"marginLeft": "-=53px"}, 500);
      $("#comments, #addComment").fadeOut(300);
    } else {
      $(".commentsSwitch").animate({"marginLeft": "+=53px"}, 500);
      $("#comments, #addComment").fadeIn(300);
    };
});

live is binding to click, however, when toggle is called, it is also bound (normally) on click. You should decide if 'live' is really what you need. For instance, if #showHideComments object is replaced via AJAX during the use of the page, then you need live and my solution. However, if it isn't swapped out and remains the same, just use the inside of your original live function (just the toggle code) and you will be golden.

Doug Neiner
Pssst, combine selectors too!
Nick Craver
@Nick, great point. Updated. thanks!
Doug Neiner
Thanks! Just what I needed. I do need to use live as the data is returned by my php script via ajax. Thanks for the optimization too, I'm still learning :)
Dave Kiss