简体   繁体   中英

jquery (hover and load) events binding on dynamically created elements

I am able to bind click event to element with class name keybox . And this element is generated dynamically.

$('body').on('click','.keybox', function(){
// some code here
});

But for same element I tried binding hover and load event using following code:

$('body').on('hover','.keybox', function(){
// some code here
});


$('body').on('load','.keybox', function(){
// some code here
});

....and its not working as expected.

Can someone help with this problem? I want to bind hover and load event to my element with class name keybox and this element is generated dynamically.

Instead of hover, use mouseenter and mouseleave event. Instead of body.load use

$(document).ready(function() {

You can use following approach to bind multiple events and get object information via event object .

$('body').bind('click hover load', '.keybox', function(e){
   if ( e.type === 'hover') {
     // do something
   }
   else if(e.type === 'click') {
    // do something
   }
   ....
});

Make sure you bind events in $(document).ready(function() {} or load javascript just in bottom of html document body.

Since hover is deprecated you should use mouseenter and mouseleave for load you can write using event using on ( load is equivalent to ready ).

 $(function(){ $(document).on('mouseenter', '.keybox', function () { $(this).css('color','red'); }); $(document).on('mouseleave', '.keybox', function () { $(this).css('color','black'); }); $(document).on('click', '.keybox', function () {// click on dynamically loaded events. $(this).css('color','green'); }); $('#btn').click(function() { $('#parent').append("<div class='keybox'>sample1</div>"); $('#parent').append("<div class='keybox'>sample2</div>"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="parent"> zdhsdhsau </div> <input type="button" id="btn" value="create"/> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM