Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.on('animationend webkitAnimationEnd oAnimationEnd') only fires once

I have an animation and after the animation is complete I use a partial view to update the data. .on('animationend webkitAnimationEnd oAnimationEnd') only seems to be firing the first time. Any idea why this is happening, it's like the JQuery isn't recognizing the $('#marqueeTop span').Here is a jsfiddle of what I would like it to do.

Partial

<div id="marqueeTop">
    <span class="moveTop">
        @foreach(var item in Model){
            <label>
                @Html.DisplayFor(x => item.GroupName)
                @Html.DisplayFor(x => item.Sales ).....
            </label>   
        }
    </span>
</div>

CSS

#marqueeTop {
    width: 100%;
    margin: 0 auto;
    white-space: nowrap;
    overflow: hidden;
    box-sizing: border-box;
}

#marqueeTop span {
    display: inline-block;
    padding-left: 100%;
    text-indent: 0;
    font-family:wallStreetFont;
}
.moveTop{
    animation: marqueeTop 5s linear infinite;
    animation-iteration-count:1;
}

JQuery

 $('#marqueeTop span').on('animationend webkitAnimationEnd oAnimationEnd', function () {
    $.get('/Home/GetBookingsTicker', function (response) {
        $('#marqueeTop').replaceWith(response);
    });
});
like image 825
joetinger Avatar asked Sep 02 '14 17:09

joetinger


1 Answers

You are attaching an eventListener on #marqueeTop span and within this listener you remove (replace) #marqueeTop. ($('#marqueeTop').replaceWith(response);)

Since you remove #marqueeTop you also remove your own eventListener (on the <span>). Here is another question as reference: If a DOM Element is removed, are its listeners also removed from memory?

You can use a delegated event handler with .on()

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector.

$('body').on('animationend webkitAnimationEnd oAnimationEnd', '#marqueeTop span', function () {
    $.get('/Home/GetBookingsTicker', function (response) {
        $('#marqueeTop').replaceWith(response);
    });
});

Like this you can remove and add the #marqueeTop and still have a eventListener on this element.

Here is a demo: http://jsfiddle.net/m95pzsau/5/

like image 148
Nico O Avatar answered Oct 15 '22 11:10

Nico O