views:

59

answers:

4

Is there another in jquery to run a function at page load and at a keyup event instead of the way I'm doing it?

$(function() { 
  totalQty(); 
  $("#main input").keyup(function() { 
    totalQty(); 
  }); 
});
A: 

You can use $(document).ready event to run functions on load:

$(document).ready(function(){ 
    /* your code here */ 
});
Andrew Bezzub
those are the same thing, I think he was referring to a better way to factor his code instead of different wording.
ocdcoder
oops, i missed that in 1.4 $() is no longer the same thing
ocdcoder
A: 
ocdcoder
for more reading goto http://api.jquery.com/live/
ocdcoder
A: 

Here's what I would do (jQuery 1.4+ )

$(document).ready(function() { 
  totalQty(); 
  $("#main").delegate("input","keyup",function() { 
    totalQty(); 
  }); 
});
David V.
why delegate instead of live? I thought live did event delegation?
ocdcoder
+1  A: 

Disregarding live or delegate optimizations, you can trigger an event like this:

$(function() { 
   $("#main input").keyup(function() { 
     totalQty();
   }).filter(":first").keyup(); //Run it once
});

No need for the filter if it's not on multiple elements, just leave it out in that case.

Nick Craver