Moein Hosseini
Moein Hosseini

Reputation: 4383

live function with out arguments in jQuery

I wanna select some item by jQuery which has been added after loading page,so I wanna use live() function.I used it before for clicking like following code:

$("selector").live('click')

but now when I wanna use it in another function. but It will not work with out argument,like it live() for e.g followin code will alert test (work)

var pos_eq=Math.abs($('.myList').css("left").replace("px","")/$('.myList').children('li').eq(0).css('width').replace("px","")) + 1;
alert("test");

but this will not.

var pos_eq=Math.abs($('.myList').live().css("left").replace("px","")/$('.myList').live().children('li').eq(0).css('width').replace("px","")) + 1;  
alert("test");

how can I solve it?

Upvotes: 1

Views: 109

Answers (3)

gilly3
gilly3

Reputation: 91557

You want a function, not a variable. It looks like you are trying to keep pos_eq up to date after elements have been added to the page. Having a variable auto-update when the DOM changes in the way you are trying to do is not possible with JavaScript. What you can do is use a function instead of a variable. This way whenever the value is accessed you are getting the latest value because it is computed on demand:

function pos_eq() {
    var list = $('.myList');
    var left = parseInt(list.css("left"));
    var width = parseInt(list.children('li').eq(0).css('width'));
    return Math.abs(left / width) + 1;
}

I broke your code up into multiple statements to make it more readable. You would use this function the same as you used the variable, but instead add parens to the end to invoke the function:

alert(pos_eq);

alert(pos_eq());

Upvotes: 1

airportyh
airportyh

Reputation: 22668

The description of live() is: Attach a handler to the event for all elements which match the current selector, now and in the future. It does not give you a live node list despite its name. jQuery does not have any method that returns a live node list(such as those returned by getElementsByTagName etc.) as far as I know.

Upvotes: 0

jfriend00
jfriend00

Reputation: 707696

To get a set of objects at the time you need them, just do $("selector"). That will do a query at that time and get the set of objects. There is no need to use .live() in order to query objects on the page. It does not matter whether the objects were part of the original page or were added dynamically later. When you do $("selector"), it will search the contents of the current page and get you the objects that are currently in the page that match the selector.

There is no way to do a live selector query and save it and have it automatically update in jQuery or any other library I know of. The way you solve that issue with a dynamic page is that you just do a new query when you need current results.

Upvotes: 0

Related Questions