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 {
  • Pankaj

    Very good info, Love the way you written.

  • hh




Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

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