The JQuery(document).ready function does not seem to be executing on the webpage, but it works as expected when placed in a

I have encountered a peculiar problem. It's strange to me because I can't figure out the root cause of it, despite trying everything in the Chrome Developer Tools debugger. Here is a snippet of code that works when I run it from a file on my desktop by opening it:

    jQuery(document).ready(
        function () {
            Slider.initModule(jQuery('#slider'));
        }
    );

I'm importing jQuery as usual:

<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>

Here is the complete page. I am perplexed, as this should just be a simple example of a chat slider taken from "Single Page Web Applications" on Manning.

<!DOCTYPE html>
<html>
<head>
<title>Slider</title>
<style type="text/css">
    body {
        width: 100%;
        height: 100%;
        overflow: hidden;
        background-color: #777;
    }
    #slider {
        position: absolute;
        top: 8px;
        left: 8px;
        bottom: 8px;
        right: 8px;
        border-radius: 8px 8px 0 8px;
        background-color: #fff;
    }
    .slider {
        position: absolute;
        bottom: 0;
        right: 2px;
        width: 300px;
        height: 16px;
        cursor: pointer;
        border-radius: 8px 0 0 0;
        background-color: #f00;
    }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
    var Slider = (function () {
        var configMap = {
            extendedHeight: 434,
            extendedTitle: 'Click to retract',
            retractedHeight: 16,
            retractedTitle: 'Click to expand',
            templateHtml: '<div class="slider"></div>'
        }, $slider, toggleSlider, onClickSlider, initModule;
        toggleSlider = function () {
            var sliderHeight = $slider.height();
            if(sliderHeight === configMap.retractedHeight) {
                $slider.animate({height: configMap.extendedHeight})
                        .attr('title', configMap.extendedTitle);
                return true;
            } else if(sliderHeight === configMap.extendedHeight) {
                $slider.animate({height: configMap.retractedHeight})
                        .attr('title', configMap.retractedTitle);
                return true;
            }
            return false;
        };
        onClickSlider = function (event) {
            toggleSlider();
            return false;
        };
        initModule = function ($container) {
            $container.html(configMap.templateHtml);
            $slider = $container.find('.slider');
            $slider.attr('title', configMap.retractedTitle)
                    .click(onClickSlider);
            return true;
        };
        return {initModule: initModule};
    })(jQuery);
    jQuery(document).ready(
            function () {
                Slider.initModule(jQuery('#slider'));
            }
    );
</script>

</head>
<body>
<div id="slider"></div>
</body>
</html>

I cannot understand why the slider works when the above HTML is accessed through a file:/// URI in Chrome but fails to work when served over a localhost server. What could be causing this discrepancy?


Here's an intriguing update.

I inserted an alert into the toggleSlider function, and the pixel values differed from the CSS!

alert("HERE! " + sliderHeight);

I received a value of 15, whereas when I save the source code and open the file, I see 16! This inconsistency seems to be the reason why the slider isn't functioning correctly for me on localhost.

Answer №1

Everything appears to be functioning correctly for me, feel free to take a look at the JsFiddle demo.

Unless the intention is for the slider to automatically open upon page load?

jQuery(document).ready(
        function () {
            Slider.initialize(jQuery('#slider'));
        }
);

Keep in mind that JQuery may not work properly on your computer if the date and time settings are incorrect.

Answer №2

Consider trying a separate script just for handling the loading process:

<script type="text/javascript">
var Loader = (function () {
    var configMap = {
        extendedHeight: 434,
        extendedTitle: 'Click to retract',
        retractedHeight: 16,
        retractedTitle: 'Click to expand',
        templateHtml: '<div class="loader"></div>'
    }, $loader, toggleLoader, onClickLoader, initModule;
    toggleLoader = function () {
        var loaderHeight = $loader.height();
        if(loaderHeight === configMap.retractedHeight) {
            $loader.animate({height: configMap.extendedHeight})
                    .attr('title', configMap.extendedTitle);
            return true;
        } else if(loaderHeight === configMap.extendedHeight) {
            $loader.animate({height: configMap.retractedHeight})
                    .attr('title', configMap.retractedTitle);
            return true;
        }
        return false;
    };
    onClickLoader = function (event) {
        toggleLoader();
        return false;
    };
    initModule = function ($container) {
        $container.html(configMap.templateHtml);
        $loader = $container.find('.loader');
        $loader.attr('title', configMap.retractedTitle)
                .click(onClickLoader);
        return true;
    };
    return {initModule: initModule};
})(jQuery);
</script>

Then proceed with creating another script like this:

<script>
jQuery(document).ready(
        function () {
            Loader.initModule(jQuery('#loader'));
        }
);
</script>

In some cases, running a script within itself may not work as expected. Separating it into distinct scripts might resolve any unexpected issues.

Answer №3

Have you tested if switching the jQuery version to 1.9 makes a difference?

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

Passing a JSON object from a Rails controller to Javascript

After creating a hash structure in Ruby like this: Track_list = {:track1=>{:url=>"https://open.spotify.com/track/2Oehrcv4Kov0SuIgWyQY9e", :name=>"Demons"}, :track2=>{:url=>"https://open.spotify.com/track/0z8yrlXSjnI29Rv30RssNI", :name=> ...

Tips for synchronizing the movement of a nested div with its parent during zoom operations

I have noticed that most posts address the issue of elements resizing or moving, but I am experiencing the opposite problem with my element. The div named headLogo, which contains the logo as a background, remains fixed and does not resize or move along wi ...

Creating a promise around a MongoDB instance in Node.js

Currently I am developing a web application where I need to create a MongoDB singleton connection that can be reused in different modules. My approach involves using promises, and so far this is what I have attempted: Server.js module.exports = new Promi ...

Troubles encountered when populating the array within a Vue component

I am experiencing an issue with my ProductCard component where the addItem method is not successfully adding a new item to the array. <template> <div class="card"> <div v-for="item in TodoItems" :key="item.id ...

How can I ensure that my SVG Image perfectly fits within the Parent wrapper div?

I've been grappling with the following code snippet. I'm struggling to make my SVG image fit within my container div. .img { margin: 0; padding: 0; overflow: hidden; width: 500px; position: relative; } img { top:0; ...

Generating dynamic strings for identifiers in JSX

Can you help me figure out how to dynamically create IDs like this? <div id="track_1"></div> <div id="track_2"></div> I tried assigning the IDs from the parent component like this: export default function Compon ...

Ways to access configuration settings from a config.ts file during program execution

The contents of my config.ts file are shown below: import someConfig from './someConfigModel'; const config = { token: process.env.API_TOKEN, projectId: 'sample', buildId: process.env.BUILD_ID, }; export default config as someCo ...

What is the best way to align a GIF and two rows of text within a container div?

Check out my JSFiddle below: In this fiddle, there is an image sized 32 by 32 on the left side and two lines of text on the right. I need help aligning the center of the gif and the text with the middle of the enclosing frame. I've tried adjusting t ...

Unable to extract query parameters from URL using Express JS as req.query returns an empty object

I came across discussions about this issue here and here, but unfortunately, the solutions provided didn't work for me. I'm attempting to extract parameters from the URL using req.query. In my server.js file, I've implemented the following: ...

Data vanished from the input field values

Having an issue with displaying an HTML table inside a .cshtml file. When I hardcode values, the table appears as expected. However, when I attempt to populate it using a foreach loop, the table disappears. <script> var nTable = ""; $(docu ...

Show SVG in its ViewBox dimensions

Currently, I am utilizing the img-Tag to showcase SVG images that have been uploaded by users onto my Amazon S3 storage. <img src="http://testbucket.s3.amazonaws.com/mysvg.svg" /> An issue arises once the image is displayed as it does not retain i ...

Content not displaying in Bootstrap tabs when clicked on

I'm struggling to fix the tab functionality on my website. Upon loading the page, the content under the first tab is visible, but once I switch to the second tab, all content disappears. Going back to the first tab reveals no content until the page i ...

Troubleshooting padding problem in mobile gallery view with Bootstrap

Having a problem with the gallery layout in Bootstrap. It looks great on desktop view, but on mobile, there's no space between images on the same row. On mobile, the images stack vertically without any spacing between them within a row. However, ther ...

Is it possible to upload a file using Angular and ASP.NET Web API Core?

I am encountering an issue with CORS policy while making requests. It works fine when the content-type is set to 'application/json'. However, when I try to upload a file using content-type 'multipart/form-data', I receive an error: XML ...

Encountering a Route Not Found Error on Heroku with Node and Express Deployment

Once I deployed my app to Heroku, it started having trouble finding the API path that was set up in Express. The code runs perfectly fine on my local machine, but on Heroku, I keep getting a 404 - Page Not Found error. This is how the router is set up: c ...

Having trouble getting the .push() method in JavaScript to function correctly

I've encountered an issue while trying to develop a function that iterates through each item in an array and records the index of a specific item when found. In this particular function, whenever the item 'contraband' is detected during the ...

Leveraging the boolean values of attributes within JSX statements

I have been working on a React.js project where I am trying to incorporate a data-picker plugin that requires a specific style of input-attributes: <input data-enable-time=true /> However, I have encountered an issue where webpack fails to compile t ...

Validation in JQuery Mobile is crucial for ensuring that user input is correct before submitting a

Trying to create a login page using JQuery Mobile, I implemented validation with the jQuery validation plugin and AJAX to post the data to a PHP server code if validation is successful. However, instead of functioning as intended, the code redirects back t ...

Transferring a PHP array to JavaScript using AJAX

I have spent time searching for answers to my issue with no success. My PHP file includes the following array: $data = ['logged' => $_SESSION['loggedin'], 'sessName' => $_SESSION['name']]; echo json_encode($dat ...

Is there a way to eliminate the whitespace beneath the "Brilliant" division?

[Screenshot of white space under div] [1]: https://i.sstatic.net/cO7TV.jpg I'm having trouble figuring out why there is visible white space here. As a coding beginner, I would really appreciate any assistance. I've tried searching for the soluti ...