Use jQuery .Toggle() with Live or Bind

By Sam Deering

Bascially in a nutshell you can use Live and Toggle together BUT for coding best practices you shouldn’t. Both jQuery .Live() and jQuery .Toggle() automatically create thier own bind events to the element. This causes problems when they are used together as you would need to click the button twice to get the Toggle to work.

A way around this is to use a Live(‘click’) event with inside Toggle event you can add the .Trigger(‘click’) command to the end of the function call like this:

// Add sort functions on dynamic elements inserted into DOM

[code lang="js"]
//function inside JQUERY4U namespace
sortClickListener: function(){

	// Find second class name
	var button = $(this).attr('class').split(' ');
	// Sort table
	$(this).toggle(function() {
	}, function() {
	}).trigger('click'); /*force the button to work with 1 click*/

Another way would be to use .Data method but this would be overkill and a long winded way of solving the puzzle.

$(".reply").live('click', function () {
    var toggled = $(this).data('toggled');
    $(this).data('toggled', !toggled);
    if (!toggled) {
    else {

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • Pankaj

    Very good info, Love the way you written.

  • hh


Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.