1

I have some Ajax loading elements. After this i need to read some data atribute of this elements on mouseenter. But something is wrong, each of loaded elements can't display data atribute.

HTML:

<label data-href="/79" data-tooltip="description" class="tooltip">some label</label>

and some JS:

var tooltip = $('.tooltip');

tooltip.on({
    mouseenter: function(){
        if ($(this).data('tooltip').length){
            $('body').append('<span class="tooltip_vwr"/>');
        ...

How to call lenght method after ajax loading? Thx for help.

Lukas
  • 6,464
  • 16
  • 61
  • 114

2 Answers2

1

try this:

$(document).on("mouseover", ".tooltip", function(e){
    //your code here
    if ($(this).data('tooltip').length){
        $('body').append('<span class="tooltip_vwr"/>');
    }
})

is better if you bind this event only when the data returned to ajax call is fully loaded. (right now i'm not sure if is better way... try first one) like:

 //EDIT - remember if this handler will trigger 2 or more time insert .off() before .on()
 var myhandler = function(){
   $(".tooltip").on(function(e){
      //your code here
      if ($(this).data('tooltip').length){
        $('body').append('<span class="tooltip_vwr"/>');
      }
    })
 }
$(function(){

   // call each time u need to rebind
   myhandler();

   $.ajax({
    //ajax option
    success : function(response){ 
       //at the end of your parsing and manipulating function you can bind event
       myhandler();
    }
   });
})

If you call ajax 2 or more time add before .on() an .off() function like:

$(".tooltip").off().on(function...

to prevent double bind.

BenMorel
  • 30,280
  • 40
  • 163
  • 285
Frogmouth
  • 1,688
  • 1
  • 11
  • 20
  • yeah but i have this action afetr and before call ajax for manny elements on site, this is tooltip, so maybe better would be create some function for it and call in and out of success? – Lukas Dec 02 '13 at 15:28
  • uhm... you can try with first soluction. Or you can try and function that contain the handler and call it in dom ready and on ajax loaded. wait i edit my answer – Frogmouth Dec 02 '13 at 15:56
1

Try using event delegation, i.e., bind the event listener to an enclosing element that is guaranteed to exist at the time of binding. For example:

$(document).on('mouseenter', '.tooltip', function() {
   //...
});

See also:

Community
  • 1
  • 1
bfavaretto
  • 69,385
  • 15
  • 102
  • 145