Skip to main content

Use jQuery .Toggle() with Live or Bind

By Sam Deering



Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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 {

Related Articles

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn the basics of programming with the web's most popular language - JavaScript

A practical guide to leading radical innovation and growth.

Integromat Tower Ad