Issue with running JavaScript functions on HTML elements in a partial when updating it with AJAX in ASP.NET MVC Core

My asp.net mvc core 2.2 application includes a page where a partial is loaded:

<div class="col-md-9" id="content">
    @await Html.PartialAsync("_TrainingContent")
</div>

The partial contains a model and loads a video using the video.js player:

@model Partner2Train.Models.ModuleViewModels.TrainingContentViewModel

@if (Model != null)
{
    <li>Do some training stuff for @Model.ModuleId</li>
    <div class="row">
        <div id="instructions">
            <video id="my_video" class="video-js vjs-default-skin" width="640" height="267"
                   poster=''
                   data-setup='{ "aspectRatio":"640:267", "playbackRates": [0.5, 1, 2], "controls":true, "preload":"auto", "autoplay":false, "inactivityTimeout":0 }'>

                <source src="~/video/sample_video.mp4" type="video/mp4" />
                <source src="~/video/sample_video.webm" type="video/webm" />
                <source src="~/video/sample_video.ogv" type="video/ogg" />
                <p>Your browser does not support HTML5 video.</p>
            </video>
        </div>
    </div>

    <div class="row" style="margin-top:25px;">
        <div id="db_data">
            <label>Current video location: </label> <input type="text" id="watched_value" value="" disabled /><br />
            <label>Total video duration: </label> <input type="text" id="total_duration" value="" disabled />
        </div>
    </div>
    <br /><br />

}
else
{
    <text>Please select a module</text>
}

Initially, when I have javascript functions running on document ready, the video loads and plays without any issues. However, when I update the partial using an ajax call:

$("#tcontent").click(function () {
    $.ajax({
        url: "Module/TrainingContent/?id=2",
        type: "get",
        //data: $("form").serialize(), //if you need to post Model data, use this
        success: function (result) {
            $("#content").html(result);
        }
    });
})

The video no longer loads after the ajax call. It seems that the javascript for the video player doesn't trigger again. To address this, I moved the video javascript into separate functions and called them upon a successful ajax call:

$("#tcontent").click(function () {
    $.ajax({
        url: "Module/TrainingContent/?id=2",
        type: "get",
        //data: $("form").serialize(), //if you need to post Model data, use this
        success: function (result) {
            $("#content").html(result);
            vidprep();
            vidbutton();
        }
    });
})

Despite this approach, the video controls still don't load correctly after an ajax update. The javascript functions run successfully but don't apply the controls to the video, displaying an unformatted box instead.

If you have any insights on how to make javascript interact with elements in a partial updated via ajax, I would greatly appreciate your assistance as I have been grappling with this issue for several days.

Elements after ajax callhttps://i.sstatic.net/rAJO1.png

Below are the two javascript functions that are running successfully, printing messages to the console:

function vidprep() {

    console.log("In partial video function");
    // Stop if HTML5 video isn't supported
    if (!document.createElement('video').canPlayType) {
        $("#video_controls").hide();
        console.log("Can't Play Video");
        return;
    }

    var video = document.getElementById("my_video");

    // Play/Pause ============================//
    $("#play_button").bind("click", function () {
        video.play();
    });

    $("#pause_button").bind("click", function () {
        video.pause();
    });

    $("#play_toggle").bind("click", function () {
        if (video.paused) {
            video.play();
            $(this).html("Pause");
        } else {
            video.pause();
            $(this).html("Play");
        }
    });

    // Play Progress ============================//
    $(video).bind("timeupdate", function () {
        var timePercent = (this.currentTime / this.duration) * 100;
        $("#play_progress").css({ width: timePercent + "%" })
    });

    // Load Progress ============================//
    $(video).bind("progress", function () {
        updateLoadProgress();
    });
    $(video).bind("loadeddata", function () {
        updateLoadProgress();
    });
    $(video).bind("canplaythrough", function () {
        updateLoadProgress();
    });
    $(video).bind("playing", function () {
        updateLoadProgress();
    });

    function updateLoadProgress() {
        if (video.buffered.length > 0) {
            var percent = (video.buffered.end(0) / video.duration) * 100;
            $("#load_progress").css({ width: percent + "%" })
        }
    }

    // Time Display =============================//
    $(video).bind("timeupdate", function () {
        $("#current_time").html(formatTime(this.currentTime));
        $("#watched_value").val(formatTime(this.currentTime));
    });
    $(video).bind("durationchange", function () {
        $("#duration").html(formatTime(this.duration));
        $("#total_duration").val(formatTime(this.duration));
    });

    function formatTime(seconds) {
        var seconds = Math.round(seconds);
        var minutes = Math.floor(seconds / 60);
        // Remaining seconds
        seconds = Math.floor(seconds % 60);
        // Add leading Zeros
        minutes = (minutes >= 10) ? minutes : "0" + minutes;
        seconds = (seconds >= 10) ? seconds : "0" + seconds;
        return minutes + ":" + seconds;
    }
}

function vidbutton() {
    var $refreshButton = $('#refresh');
    var $results = $('#css_result');
    console.log("In video button");
    function refresh() {
        var css = $('style.cp-pen-styles').text();
        $results.html(css);
    }

    refresh();
    $refreshButton.click(refresh);

    // Select all the contents when clicked
    $results.click(function () {
        $(this).select();
    });
}

Answer №1

Did you remember to add the JS file and check for any debugging errors in the browser?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Instructions on deactivating the background when the sidebar is displayed and closing the sidebar by clicking anywhere other than the sidebar

I'm in the process of creating a sidebar for my website. When the sidebar is displayed (by clicking showRight), I want to disable the background content so that the user can't interact with anything outside of the menu. If the user clicks on th ...

Tips for retrieving data from Angular Material Table source

It's great to see everyone doing well! I'm facing an issue with rendering data to a material table, and I can't figure out why it's not working. When I try to assign the data to the table's datasource for rendering, the information ...

Grouping an array of dynamic objects by a property value in react js / javascript: A step-by-step guide

There is an object in the following format: [{"genericName":"genesName test","genericId":3,"code":"generics"},{"genericName":"genesName fhfghsd","genericId":8,"code": ...

I've recently delved into the world of JavaScript and am currently working on creating a calculator website. However, I'm facing some challenges in getting it to function

I created a calculator code using HTML, CSS, and JavaScript for a website. However, due to my limited experience with JavaScript coding, I encountered some issues. Currently, I have only implemented the number input part (not operations or deletion), but w ...

What is the best way to smoothly scroll to another page using a specific id?

My website consists of multiple pages and I am looking for a code that will allow for smooth scrolling navigation to another page when loading on a specific id or section. For example, in the navbar I have multiple pages with links. When clicking on a lin ...

How come useEffect runs only once even when multiple states in the dependency array of useEffect change simultaneously?

<div onClick={() => { updateValue1((x: number) => x + 1); updateValue2((x: number) => x + 3); }} > one? two? </div> const [value1, updateValue1] = useState(1); const [value2, updateValue2] = useState(1 ...

Sort arrays in Javascript by their respective lengths

Is there a way to arrange these arrays in descending order of the number of items they contain? I believe the logic is correct, but I might be missing some essential methods. The current output is empty. //Declare Variables var TN = ['Chattanooga&apo ...

Issue with npm configuration permissions

I am encountering permission issues when using the npm config command. It appears that there is an attempt to alter the owner of my ~/.npmrc file without authorization. Upon executing npm config set color false, I encounter the following error: npm ERR! E ...

The functionality of HTML5 canvas image objects is not functioning as expected

I have been working on a function to retrieve an image object using HTML5 canvas, but I keep encountering an error alert (onerror event) function FetchImage() { var img = new Image(); img.src = "http://localhost/assets/images/loadedsprite.png"; ...

Next.js is like Gatsby but with the power of GraphQL

I'm curious if it's possible to set up GraphQL in Next.js similar to how it's done in Gatsby, allowing me to query pages and retrieve data from them. Are there any plugins available for Next.js that work like Gatsby-file-source and gatsby-ma ...

Can someone help me figure out how to trigger my function after my jQuery 'each' function has completed along with all the AJAX calls it includes?

Hello all, seeking some guidance here. I have experimented with various solutions from SO and other sources. This particular one caught my attention as I tried to ensure that my function wouldn't execute until all ajax calls were completed. However, I ...

Creating a custom progress bar using Javascript and Jquery

I developed a progress bar that is fully functional. Here is the HTML structure: <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style ...

Utilizing the Vuetify Dialog Component in a repetitive manner to confirm the deletion of an event

In a project I'm working on, there's a 'datatable.vue' file that loops through data and displays it in a table. Within this loop, I want to implement a reusable dialog component from Vuetify (v-dialog) that will load upon interaction wi ...

Having difficulty converting a list of intricate objects into a CSV format

I am faced with a challenge of handling an array of complex objects, some of which may contain arrays of more objects. My goal is to convert this data into a CSV file. However, whenever there is a list of objects, the information appears as [object Object] ...

Next.js production build encountering an infinite loading error

I have been utilizing the Next.js TypeScript starter from https://github.com/jpedroschmitz/typescript-nextjs-starter for my current project. The issue I am facing is that when I attempt to build the project after creating numerous components and files, it ...

Can I insert JavaScript code in any location within an HTML file?

Typically, Javascript code is placed in the header section of HTML code. <head> <script type="text/javascript" language="javascript" src="core.js"></script> ... </head> However, I've tested putting Javascript code in the body ...

Step-by-step guide for implementing an "on change" event for a select box within a dialog box

I recently wrote an HTML code snippet like this: <div id = "dialog-1" title = "Dialog Title goes here..."> <select id= "lang" name= "lang"> <option value="1"> TEXT </option> <option value="2"> HTML </op ...

"Is there a way to loop through elements in JavaScript similar to how you

When working in bash, I typically use the following code: for i in {0..2}; do echo x$i; done However, when attempting to replicate this function in JavaScript with the following code: for (var i=0; i<3; i++) { console.log(x$i); }; It is evident t ...

Creating a unique custom view in React Big Calendar with TypeScript

I'm struggling to create a custom view with the React Big Calendar library. Each time I try to incorporate a calendar component like Timegrid into my custom Week component, I run into an error that says react_devtools_backend.js:2560 Warning: React.cr ...

Experience an enthralling carousel feature powered by the dynamic ContentFlow.js

My website features a cover flow style carousel with 7 images: <!-- ===== FLOW ===== --> <div id="contentFlow" class="ContentFlow"> <!-- should be place before flow so that contained images will be loaded first --> <div class= ...