user2067567
user2067567

Reputation: 3813

JQuery Live vs On

i have the below code which was working fine with Live

 $('.numbersonly').live('keydown', function (e) {
    var key = e.charCode || e.keyCode || 0;
    return (key == 8 || key == 9 || key == 46 || (key >= 37 && key <= 40) ||
           (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});

And i changed to On

 $('.numbersonly').on('keydown', function (e) {
    var key = e.charCode || e.keyCode || 0;
    return (key == 8 || key == 9 || key == 46 || (key >= 37 && key <= 40) ||
           (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});

But am getting script error in min.js file . Am i missing something?

Upvotes: 1

Views: 1626

Answers (2)

Adil
Adil

Reputation: 148178

Delegate event to parent of .numbersonly or document otherwise

$(document).on('keydown', '.numbersonly', function (e) {
    var key = e.charCode || e.keyCode || 0;
    return (key == 8 || key == 9 || key == 46 || (key >= 37 && key <= 40) ||
       (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});

Upvotes: 6

Kovge
Kovge

Reputation: 2019

If you bind events with on, the events will be binded only for the Current DOM elements (that matching your selector) So that is recommend , that use on , 'after' domready event.

example:

  $(document).ready(function(){
         ...
         $('selector').on('event',eventHandler(e){
             ...
         });
  });

If you use live, the events will binding to matched elements after modify the dom tree too. (For example you load content with ajax)

Upvotes: 0

Related Questions