zipzapduo
(Zipzapduo)
July 12, 2012, 8:18pm
1
i have a script jquery like this:
$(".play").toggle(function.....)
when i load the page with a CListView everything is fine and the toggle function works when i click in play <a> element.
The problem is when i click on next page on CListView pagination the <a> inside the list doesnt work anymore,the toggle doesnt trigger.
Newb
(Antowka2010)
July 13, 2012, 6:57am
2
May be your code looks like
$('.play').click(function(){//toggle});
So it may happen that when page loads, click event on play is binded ok. But after you change your page, .play is new and binded click event doesn’t work anymore.
zipzapduo
(Zipzapduo)
July 13, 2012, 8:41am
3
Yes this is the problem but how to solve it?
Newb
(Antowka2010)
July 13, 2012, 10:40am
4
Jquery have methods (live, on, bind) that allow you to bind event for all selectors, event that not on the page at document.ready.
zipzapduo
(Zipzapduo)
July 13, 2012, 11:00am
5
But i already have the live,my entire script:
Yii::app()->clientScript->registerScript('audio','
var audio=new Audio();
$(".play").live("click",function(event){
var ficheiro="'.Yii::app()->request->baseUrl.'/assets/audio/"+$(this).attr("id");
$(this).toggle(function() {
if (audio.canPlayType) {
if (audio.canPlayType("audio/mpeg")) {
audio.src=ficheiro+".mp3";
}
else{
audio.src=ficheiro+".ogg";
}
}
audio.play();
$(this).find("img").attr("src","/images/stop.png");
}, function() {
audio.pause();
audio.setCurrentTime=0;
$(this).find("img").attr("src","/images/Button-Play-icon.png");
}).trigger("click");
});
', CClientScript::POS_READY);
masapri
(Mas Apri)
August 24, 2012, 10:22am
6
Hi zipzap,
I was having the same problem, and here’s my conclusion:
For dynamic element generated by ajax, you can’t directly bind an event to it as the binding will lost whenever the elements are updated by ajax.
Try using delegate:
http://api.jquery.com/delegate/
Select DOM parent of the dynamic element (usually the one which encloses Clistview) and then delegate the click event to its dynamic child, in your case $(".play").