Bunghole
Bunghole

Reputation: 55

jQuery hover AJAX loaded content not working

I get content though AJAX like:

<div class="nachricht" id="1">
    bla
    <div class="detail" id="1" style="float: left; display: none;">hidden stuff</div>
    <div class="spacer" style="clear: both;"></div>
</div>

and I want .details to be shown on hover on .nachricht

so I use:

$(".nachricht").hover(function(){
    $(".detail", this).stop(true,true).delay(500).show(0);
    }, function (){
    $(".detail", this).stop(true,true).delay(500).hide(0);
});

Why isn't it working when loaded though AJAX and how could I solve it?

EDIT:

I get the content from functions like:

function loadfile(){
    $.ajax({
        type: 'post',
        url: 'donachrichten.php',
        data: {mach: "loadfile", kontaktfile: kontaktfile},
        success: function(data){
             $("#chatnow").html(data);
        }
    });
}

Upvotes: 1

Views: 2907

Answers (2)

partypete25
partypete25

Reputation: 4413

Why not handle the show/hide with css instead? First, remove the inline styles from the .detail div, then add this to your stylesheet.

.detail {float:left;display:none}
.nachricht:hover .detail {display:block;}

Otherwise wrap your initial hover function in a function.

function showDetails(){
$(".nachricht").hover(function(){
    $(".detail", this).stop(true,true).delay(500).show(0);
}, function (){
    $(".detail", this).stop(true,true).delay(500).hide(0);
});
}

and call it after the data has been loaded.

success: function(data){
         $("#chatnow").html(data);
         showDetails();
    }

Upvotes: 1

xiidea
xiidea

Reputation: 3394

You can try using this:

 $("#chatnow").on('mouseenter', '.nachricht', function( event ) {
    $(".detail", this).stop(true,true).delay(500).show(0);
}).on('mouseleave', '.nachricht', function( event ) {
    $(".detail", this).stop(true,true).delay(500).hide(0);
});

explanation

As .nachricht class item doesnot exist when the your page loaded, you can't bind event with non-existing element. instead use event delegation on element #chatnow should work.

Here are some more example of hover event delegation

Upvotes: 2

Related Questions