miko7358
miko7358

Reputation: 1101

How to use live() in ajax success callback

I'm working on a wordpress site which display articles using AJAX. I added some jquery code in the success callback. One of my needs is to display an image on mouse over. All my code works except the mouse over effect.

So this is my ajax function :

function loadArticle(pageNumber, loop, term){    
    $.ajax({
        url: ajax_var.url,
        type:'POST',
        data: someData, 
        success: function(html){
            // This will be the div where our content will be loaded
            $("#content").append(html);    

            // Zoom box
            $('img.static').hide();
            $(".ad-preview").live({
                mouseover: function() {
                    $(this).find('img.static').stop().fadeIn();
                },
                mouseout: function() {
                    $(this).find('img.static').stop().fadeOut();
                }
            });

            //  Other stuff...
        });

        return false;
    }

});

and the HTML :

<div class="ad-preview">
    <a target="_blank" href="">
        <img src="img/zoom.png" /></a>            
    </a>
</div>

What is the good way to implement this effect ?

Upvotes: 0

Views: 1043

Answers (2)

tvanfosson
tvanfosson

Reputation: 532575

First, you should probably be using on rather than live. Second, delegated handlers don't have to be applied in the callback. Because they are delegated to a higher level element that remains on the page you can apply them on page load.

    $("body").on('mouseover', '.ad-preview', function() {
            $(this).find('img.static').stop().fadeIn();
    })
    .on('mouseout', '.ad-preview', function() {
            $(this).find('img.static').stop().fadeOut();
    });

Upvotes: 2

Kai Qing
Kai Qing

Reputation: 18843

.live is an active listener replaced by .on

You would place this outside the ajax call, at the base level in js - so in other words, not inside a document.ready call or inside other functions. It will work on dom elements loaded in via ajax.

Upvotes: 2

Related Questions