Question

<input type="text" id="sShState" />
$('#sShState').liveSearch(); // A plug-in
// inside plug-in:
$this = $(this);

// On focus I add a dropdown box and add li's;

var obj = '<ul id="ddList"></ul>';
$this.after(obj);
$this.next('ul').html(li's);

$('#ddList').live('mouseenter', function(){
    var $li = $this.next('ul').children('li');
    $li.removeClass('hoverLi');
    $li.hover(function(e){
        $li.filter('[last]').removeAttr('last');
        $(this).addClass('hoverLi');
    },function() {
        $li.filter('.hoverLi').attr('last', true);
        $li.filter('.hoverLi').removeClass('hoverLi');
    });

    $li.click(function(){
        selectLi($(this));
        removeList ();
    });
});

In Chrome it is very very fast!!

But in Firefox when the mouse enters for the first time over the ulbox it takes between 1-2 sec until it starts to execute the code.

Even in Internet Explorer 7 it works fine. The hovered li remains a little behind, but it starts executing immediately when the mouse enter the ul box.

Was it helpful?

Solution

You seem to have event assignment code inside of another event. So whenever the 'mouseenter' event takes place it is re-assigning the 'hover' and 'click' events. You should attach those events once outside of the live() function.

I don't know your page structure, so this may not be entirely correct. But it does illustrate the problem.

$('#ddList').live('mouseenter', function(){ 
    var $li = $this.next('ul').children('li'); 
    $li.removeClass('hoverLi');         
});

$('#ddList li').hover(function(e){  
      // $(this).filter('[last]').removeAttr('last');
      $(this).addClass('hoverLi');
},function() { 
      // $(this).filter('.hoverLi').attr('last', true);
      $(this).filter('.hoverLi').removeClass('hoverLi');
});

$('#ddList li').click(function(){
      selectLi($(this));  removeList ();      
});

I'm not entirely sure what's going on in your code, but if your intention was to make sure that events get attached to dynamically created 'li' elements, then you would need to use .live() like you did for 'mouseenter'.

$('#ddList li').live('mouseover', function() {...

$('#ddList li').live('mouseout', function() {...

$('#ddList li').live('click', function() {...

EDIT: Explanation of click() vs live()

If I have a <div id='mydiv'></div> in HTML, then all I need to do is assign the following to attach a click event:

$('#mydiv').click(function() {
    // whatever I want to do on click
});

But if the div is being dynamically added to the DOM, then I can use live() instead, and jQuery will automatically assign an event whenever I dynamically add the element.

$('#mydiv').live('click', function() {
    // whatever I want to do on click
    // jQuery takes care of assigning it to mydiv when dynamically added to DOM
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top