kkatwork
1 month ago

Javascript events sometimes don't work

Posted 1 month ago by kkatwork

Hello,

In my application I am using javascript video element events like, onplaying, onpause, onstalled etc.

The problem is, these elements do not get fired everytime. It works good and after sometime it doesn't. Using the same browser. Tried in different browsers, sometimes events fire, sometimes don't.

The video elemnt is dynamically created and it is inside a modal. The modal is shown after video element is created inside it's body. This all is a part of ajax request success method of jquery.

I have tried to add event listeners after adding the dynamic html. I have also tried to attach listners immediately after document is ready.

I have attached some code..

$('#abcModalBody').empty();
    // console.log("Body emptied");
    // AJAX request
    $.ajax({
        url: '/abc/url',
        type: 'post',
        data: {transId: id},
        success: function(response){
            data = JSON.parse(response);
            if(addHtmlToModal()) {
                addVideoEventListeners();
                // Display Modal
                $('#abcModal').modal('show');
            }
        }
    })
function addVideoEventListeners() {
    video = document.getElementById('video');
    // console.log(video);
    fillItemsTime();
    if (video && firstItemsTime() > 0) {
        video.onplay = function() {
            // alert("Play event fired");
            console.log('play event fired');
        }
        video.onplaying = function() {
            startDisplay();
        }

        video.onpause = function() {
            // console.log("Paused");
            clearTimeout(timer);
        }

        video.onwaiting = function() {
            // console.log("waiting event fired");
            clearTimeout(timer);
        }

        video.onstalled = function() {
            clearTimeout(timer);
        }

        video.onseeking = function() {
            // console.log("seeking");
            clearClassesOfAllRows();
            clearTimeout(timer);
        }

        video.onended = function() {
            index = 0;
            clearClassesOfAllRows();
        }
    }
    // console.log("Before play");
    video.oncanplaythrough = function() {
        // console.log("video can be played now");
        $('#video').get(0).play();
    }
}

Please sign in or create an account to participate in this conversation.