JavaScript
Article
By Sam Deering

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
$('.sort').live('click',JQUERY4U.sortClickListener);

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

	// Find second class name
	var button = $(this).attr('class').split(' ');
	// Sort table
	$(this).toggle(function() {
		$('.item').tsort('.'+button[1],{order:'desc'});
	}, function() {
		$('.item').tsort('.'+button[1]);
	}).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.

--ADVERTISEMENT--

$(".reply").live('click', function () {
    var toggled = $(this).data('toggled');
    $(this).data('toggled', !toggled);
    if (!toggled) {
        x1();
    }
    else {
        x2();
    }
});
Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account