Tips for utilizing the .ready() function within the .load() method

With the implementation of a jQuery script on my website, I have created a dynamic platform where the main content changes as you navigate without fully reloading the page. However, there is an issue with the .load() function in jQuery that interferes with other JavaScript/jQuery codes called within the dynamic container. To address this, I had to modify the script to include these external calls during loading.

$(function () {

if (Modernizr.history) {

    var newHash = "",
        $mainContent = $("#main-content"),
        $pageWrap = $("#page-wrap"),
        baseHeight = 0,
        $el;

    $pageWrap.height($pageWrap.height());
    baseHeight = $pageWrap.height() - $mainContent.height();

    $("nav").delegate("a", "click", function () {
        _link = $(this).attr("href");
        history.pushState(null, null, _link);
        loadContent(_link);

        return false;
    });

    function loadContent(href) {
        $mainContent
                .find("#guts")
                .fadeOut(200, function () {
                    $mainContent.hide().load(href + " #guts", function () {

                    // External script calls are included here during loading.

                        $.getScript('tablecloth/tablecloth.js', function () {
                            tablecloth();
                        });

                        $.getScript('js/domtab.js', function () {
                            domtab.init();
                        });

                        // This one is the one which doesn't work.
                        $.getScript('js/onReady.js', function () {
                        });

                        $mainContent.fadeIn(200, function () {
                            $pageWrap.animate({
                                height: baseHeight + $mainContent.height() + "px"
                            });
                        });
                        $("nav a").removeClass("current");
                        console.log(href);
                        $("nav a[href$=" + href + "]").addClass("current");





                    });
                });
    }

    $(window).bind('popstate', function () {
        _link = location.pathname.replace(/^.*[\\\/]/, ''); //get filename only
        loadContent(_link);


    });

} // otherwise, history is not supported, so nothing fancy here.


});

Additionally, I have a separate script for a specific page utilizing the .click() function (onReady.js):

$(document).ready( function() {
var maxHeight = document.getElementById("flip1").scrollHeight;
var maxHeight2 = document.getElementById("fli1A").scrollHeight;

var parent = document.getElementById("flip-container");
var DivContainerHeight = $('#text1').scrollHeight;

$("#text_var").html(maxHeight2);
//alert(DivContainerHeight);
//document.getElementById('tooltip6').style.display = 'block';
document.getElementById('global').style.height = DivContainerHeight + 'px';
//$("#flip-tabs").css({ height: maxHeight+'px' });
$("#flip-tabs").css({
    'height': maxHeight2 + 'px'
    //'height': '1300px'
});



$('#fl1A').on("click", function (e) {
    $("#fli1A").show();
    var maxHeight2 = document.getElementById("fli1A").scrollHeight;
    //alert("New height: " + maxHeight2);
    $("#text_var").html(maxHeight2);
    $("#flip-tabs").css({
        'height': maxHeight2 + 'px'
        //'height': '1000px'
    });
});

// Additional functions for click events...

});

The code functions correctly when initially loaded on the designated page (A.html), but subsequent visits after navigating away and returning cause issues with the onReady.js script. It seems like the getscript call only works upon the first page load. However, tablecloth() and domtab() scripts function properly on each visit to any page.

Each page header includes:

 <script type ="text/javascript" src="js/onReady.js"></script> 

Although it appears redundant in its current setup.

Is there a way to ensure that the onReady script loads exclusively when accessing the A.html page?

Answer №1

Try replacing $(document).ready with the function pageLoad().

This function is triggered by the ScriptManager on a page, ensuring it runs even after a postback.

It seems like your changes are not persisting during postbacks, which may be causing the issue.

I hope this suggestion proves useful to you. Best wishes!

Answer №2

One effective way to add events for dynamically generated content is by using jQuery's .on() method within the doc ready function. By doing so, you can avoid having to attach listeners each time a load function is called. For more information on this method, check out http://api.jquery.com/on/

Answer №3

After some troubleshooting, I managed to find the solution. I replaced the code in onReady.js with the following:

this.tabHeight = function () {

    codes......

};

window.onload = tabHeight;

Then, within the .load() function, I called it like this:

  $.getScript('js/onReady.js', function () {
             tabHeight();
  });

Interestingly, I realized that I simply emulated the approach taken by tablecloth.

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

No changes were seen in CSS animation when using ng-repeat in AngularJS 1.3.1

Recently delving into the world of AngularJS and I seem to be missing something. I attempted a basic CSS animation [plunker][1] but it doesn't seem to be working. Any suggestions or assistance would be greatly appreciated. Thanks in advance! [1]: htt ...

Guide to invoking a server-side function through JSON data?

Here is the code I am working on: <script type="text/JavaScript> var myarray = new array(); function getsvg1() { $.ajax({ alert("hello"); type: "post", url: "WebForm1.aspx/getsvg1", ...

Using both em and px units to add padding in CSS styling

Can padding be achieved using a combination of pixels and em units? For example, is it viable to apply padding-left with 2em plus 1px? Here's an illustration: padding-left: 2em + 1px; ...

Verifying authentication on the server and redirecting if not authorized

I am working on my NEXTJS project and I want to implement a feature where the cookie headers (httponly) are checked and the JWT is validated server-side. In case the user is not logged in, I would like to respond with a 302 redirect to /login. I'm unc ...

Discovering the following div

<button class="volumen-btn" onclick="niceFunction()> <i class="fa fa-volume-up"></i> </button> <div class="volume-control-container" id="container1" style="display:none;"> <input type="range" name="blabla" class="volume-ran ...

Unable to integrate Express.js into my React JS project

Having trouble integrating express.js into my react js Project. After adding the following lines to my app.js code: const express = require('express') const app = express(); I encounter the error messages below: - Module not found: Error: Can&ap ...

The onchange function in JavaScript is malfunctioning

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Product page</title> <!-- Fonts -- ...

How do I go about utilizing or bringing in those constants within the Drawerr.js module?

Currently, working with Next.js, I have defined some constants in the Nav.js file: export default function NestedList() { const [value,setValue]=React.useState(); const theme=useTheme(); const isMatch=useMediaQuery(theme.breakpoints.down('lg&apo ...

The onsubmit function is not successfully executing the JavaScript function

This code contains a form for creating a new user login. Upon pressing the 'continue' button, it is supposed to call the 'validateForm()' function which checks the values entered in the form. However, even when there are errors such as ...

When sending JSON Object Attributes through Angular $http, PHP will display either "{" or "["

This issue is really throwing me for a loop - I've searched high and low online but can't seem to find anyone else experiencing it. My setup involves using Angular to send form data to a PHP page, with the POST data being retrieved using the file ...

What is the best way to incorporate this HTML and script into a React component?

After receiving the embedded HTML and script from a platform, I discovered that a button triggers the script. It was originally designed to be embedded on a website, but I am attempting to integrate it into a React application. Here is the code provided fo ...

Trouble with Leafletjs Routing Machine collapse button loading issue

In my project, I am using django 1.10.5, booststrap 4.0, and LeafletJs 1.0.3 along with the routing machine plugin and geocoder. However, I have encountered an issue where the collapse button of the control panel for the routing machine does not appear (it ...

Creating a dynamic design with a responsive background image and three columns of engaging content placed on top using Bootstrap

I'm struggling to translate a design mockup into Bootstrap 3.3.6 Here is an image showcasing the concept I am aiming for: https://i.sstatic.net/1jZmh.png The blue background represents an image, with grey text boxes overlaid on top (one of which in ...

Issue with the first-child selector

Is this supposed to work or am I losing my mind? .project.work:first-child:before { content: 'Projects'; } .project.research:first-child:before { content: 'Research'; } <div class="project work"> <p>abcdef</p> ...

Numerous perspectives within an angular.js application

Issue I'm currently working on creating a product list with the following initial features: Server-side pagination Server-side filtering I am facing several challenges with my current setup, but the main issue is that I can't figure out how to ...

What is the process for uploading an image encoded in base64 through .ajax?

I am currently working with JavaScript code that successfully uploads an image to a server using an AJAX call. Here is the ajax call snippet that is functioning properly. $.ajax({ url: 'https://api.projectoxford.ai/vision/v1/analyses?', ...

Update the class name of an element depending on the URL

Hey there! I'm working on customizing the style of some elements (specifically tds within a table) based on the current URL. Here are the pages I'm targeting: http:\\domain\site\welcome.html http:\\domain\site& ...

Enhancing User Experience with jQuery: Creating Drag-and-Drop Sort

I'm looking for advice on how to create sortable lists with draggable labels. I have experience with sortable lists, but I want to take it a step further by making the items draggable so they can be easily rearranged. I tried nesting one list within a ...

Incorporating an HTML element into a Vue template

I'm currently utilizing a chart component (Chartist) that needs an HTML element to serve as a parent during SVG rendering. The elements that the chart requires are generated within a v-for loop, meaning they are not part of the DOM when the chart is ...

confused by the lack of guidance on manipulating arrays within the Autocomplete widget using Ajax

I am trying to work with an Autocomplete feature using geonames.org cities in the source option, but I'm facing some challenges when it comes to manipulating the arrays in the results. Despite having a test version that's "hard coded" and working ...