0

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.

Savaratkar
  • 1,974
  • 1
  • 24
  • 44
  • you need to make sure that the element is already present from the DOM before binding the event handlers, how are you executing your binding method? – Roljhon Jan 28 '17 at 10:24
  • Refer this: http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Ganesh Yadav Jan 28 '17 at 10:35
  • my JS file is a content script inside a chrome extension. Its loaded after the actual page load. i.e., `body` is loaded – Savaratkar Jan 28 '17 at 12:25

3 Answers3

0

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

$(document).ready(function() {
Yogesh Kumar Gupta
  • 1,009
  • 1
  • 10
  • 10
0

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.

mumair
  • 2,768
  • 30
  • 39
0

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"/>
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44