Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery Plugins with live()

I have a page that dynamically loads content with the jQuery load() function, so I need to use live() for each of my jQuery functions on this page. However, I am unable to get live() to work with jQuery plugins. For example, I want to use jQuery accordion:

$("#accordion").accordion();

But I cannot find the right syntax to get accordion to work with live(). I have tried:

$("#accordion").live("load", accordion());
$("#accordion").live("load", $("#accordion").accordion());
$("#accordion").live("load", $(this).accordion());

I either receive the "b is undefined" error, or "accordion is not defined."

like image 624
Jarred Avatar asked Feb 25 '23 10:02

Jarred


2 Answers

You must use anonymous function

$("#accordion").live('load',function(){
    $(this).accordion();
});

Edit:

If the accordion is already in the page when you first render it, then you shouldn't call it using live(), but by page load

$(function(){
    $("#accordion").accordion();
});
like image 69
Ortiga Avatar answered Mar 05 '23 12:03

Ortiga


This could partly answer your question:

I would suggest using livequery instead to do this:

$("#accordion").livequery(
  function() { $(this).accordion(); }, 
  function() { $(this).accordion("destroy"); }
);

The first function will initialize jQuery UI's accordion functionality on any $("#accordion") element that's added to the DOM, and the second one will destroy the accordion object when that same element is removed from the DOM.

like image 44
iam3v4n Avatar answered Mar 05 '23 11:03

iam3v4n