Execute Javascript/Jquery upon partial content loading

From what I can see, most of the examples and answers show how to run a partial's JavaScript when the page initially loads.

In this case, the partial doesn't load until later, triggered by a button click using AJAX.

I have experimented with placing my JS code inside:

$(document).ready(function () {

AND :

$(function(){

AND :

By itself

The first method doesn't work at all. The second and third methods seem to trigger only on the second page load. This is likely because the div that my JavaScript affects does not exist initially. So my question remains: How do I make it run when the partial loads?

Answer №1

$(document).ready(function () {
    ...
});

When the page is loaded, the $(document).ready function will be triggered. This event is connected to either document.DOMContentLoaded or window.loaded events. However, when loading partial content via ajax, the page load event has already occurred by the time the partial is loaded.

If you are using jQuery to load a partial page through ajax, it is recommended to call your function like this:

$ajax(...
}).done(function (data) {
    yourFunction();
});

Alternatively, if you are using the AjaxHelper class (e.g. with razor @Ajax.ActionLink(...)), you can utilize its AjaxOption's OnSuccess or OnComplete property to include your JavaScript function. Here's an example:

@Ajax.ActionLink("Load partial", "MyPartialAction", new AjaxOptions
{
    UpdateTargetId="partialContainer",
    OnSuccess="partialLoaded"
}

This code will load the Partial returned from the MyPartialAction action into the element with the id "partialContainer". After the partial is loaded, your JavaScript function named partialLoaded will be executed.

Answer №2

To ensure that a script runs when a partial loads, you should include it in the callback function of the request issuer for the partial content. For example, if the request issuer is using jQuery, the code would look something like this:

$.get(url, function (result) {
    // Add your custom script here within the success callback.
});

If you are utilizing an MVC helper method like Ajax.ActionLink, you can specify a jQuery function to execute upon receiving a response:

@Ajax.ActionLink("NameOfLink", "ControllerAction", new AjaxOptions
{
    HttpMethod = "GET",
    OnSuccess = "javascriptFunction(data)"
})

function javascriptFunction(data) {
    // Implement your desired functionality here
}

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

Implementing MUI createTheme within Next.js

After switching from material-UI version 4 to version 5.5.0 in my project, I encountered issues with createTheme. The colors and settings from the palette are not being applied as expected. Current versions: next: 11.0.0 react: 17.0.2 mui : 5.5.0 theme. ...

Unusual behavior exhibited by dynamic code in iframe

When trying to retrieve a dynamic height iframe, I implement the code below. In the <head> area <script language="javascript" type="text/javascript"> function adjustIframe(obj) { obj.style.height = obj.contentWindow.document.body.scrollHeight ...

What is the method to update a div containing the video title when a user clicks on a related video?

How can I make a div update with the title of the currently playing video when a user clicks on another video? I am having trouble finding an event in the API that lets me know when the video source has changed. Is there a specific event I should be listen ...

Tips for aligning elements of varying heights

Currently, I am tackling a responsive web design challenge involving floating multiple items in 4 columns side by side. The issue arises due to the varying heights of these items, causing the floating to behave improperly. Here is the current problem illu ...

Exporting a function to another class using the default export is a common practice

I'm working with two classes, Orders.js and api.js. In api.js, I need to invoke a function called ShowAlertWithDelay. However, due to the existence of a default export named mapStateToProps, I am unable to declare another export. Below is the code sni ...

What is the best way to generate a complete PDF of a webpage using pdfmake?

I'm currently developing a web application and facing the task of converting an HTML page, which contains multiple tables and datatables, to a PDF format. To achieve this, I've chosen to utilize the library pdfmake. Below is the script that I ha ...

Dropzone.js: Creating a personalized file explorer to include files that have already been uploaded

Don't worry, this isn't your typical "can't load files from the server" query... I'm looking to allow users to view files on the server in a bootstrap modal and then select specific files. After selection, I want to close the modal and ...

Tips for eliminating the undefined/null values from an array nested within another array in Angular

DATA = [{ application: [{ name: 'Room1' },{ name: 'Room2' },{ name: 'Room3' },{ name: 'Room4' },{ name: 'Room5' }], name: 'Batch 1&ap ...

A method for utilizing wildcards in conjunction with the .load function

Currently, I am utilizing jquery, jquery mobile, js, html, and css within Phonegap to develop my android/ios application. However, my understanding of js & jquery is somewhat limited. In my index.html file, I use .load to load other html files into s ...

Exploring Best Practices for Coding in node.js

Method 1: Constructor and Prototype Objects function Database(url) { this.url = url; } Database.prototype.info = function (callback) { http.get(this.url + '/info', callback); }; Method 2: Closures Approach function Database(url) { ...

Ways to send a JSON object to an MVC controller

I am looking to pass 2 arguments to my controller: an id and an object[]. Below is the code for my controller: [HttpPost] public string SaveCoordinates(string Id, object[] pFrame) { string result = "ERROR"; if (pFrame != null) { try ...

jQuery UI Tabs: Issue with JSON data not showing up

Currently, I am utilizing jquery UI tabs along with ajax functionality. The JSON data format that the ajax will be receiving looks like this: [ { "title" :"a note", "type" :"text", "content" :"MY FIRST NOTE!" }, { "title" :"t ...

Angular JS is patient when waiting for asynchronous requests to complete

Once upon a time in a factory httpFactory.factory('setFavorability', function($http){ return{ Like: function(id){ return $http.get('http://localhost:51265/Film/Like/' + id); } } ...

Designing webpages by superimposing text onto images with customizable positioning

My current project involves developing an HTML document with a floor plan image as the main layer. On top of this image, I need to display employee names extracted from a database and positioned on the map based on a location variable within the database ...

Locate the word or phrase without a comma

I am currently working on a code that involves finding keys with string values separated by commas. var db = { "name": "Nkosana", "middle": "Baryy", "surname": "walked", "batch_number": "test,b", "temp": ",,67,6,87,86,5,67865,876,67" ...

Identification error detected by server

Could anyone point out my mistake? <asp:TextBox ID="txtComentario_<%# Eval('Id').ToString() %>" TextMode="MultiLine" runat="server"></asp:TextBox> Issue Found Parser Error Message: The server is not formatted correct ...

When viewing a React data table in Chromium browsers, the columns on the right side may flicker when the screen is small or the browser

I recently integrated the React data grid Npm package by adazzle. You can find more information about it here. I encountered an issue which you can see in this example: https://codesandbox.io/s/react-data-grid-example-9sb93?file=/src/App.tsx When using a ...

Is your Jquery validation malfunctioning?

I am currently facing a challenge with required validation on an asp.net page. In order to validate the inputs, I have implemented multiple controls which can be hidden or displayed based on certain conditions. These controls include checkboxlists, dropdow ...

Choosing an item from a dropdown menu in C# using Selenium in web assembly is proving to be ineffective

I am currently working on some automated tests using Selenium Web driver. I have been able to write a script that can locate the class, but I am facing difficulties in selecting one of the items from the drop down menu. Here is the script I have so far: ...

Webpack is ejected from watch mode

Currently, I am in the process of learning React and have decided to use webpack alongside it. However, I seem to be facing an issue with webpack when it comes to the watch mode. It builds the files once but then halts. The console output reflects the foll ...