Could the absence of an external style sheet for CSS be hindering the execution of my code?

A generous Stack Overflow user provided me with the code you see here and their JSFiddle can be accessed at http://jsfiddle.net/f18513hw/. The code functions properly in JSFiddle. I copied and pasted the code into my Textpad, saved it in my htdocs folder of XAMPP, and attempted to run it.

Upon testing, I noticed that when I hover over the car icon, it magnifies as expected, but no textbox appears below the icon. The main purpose of my webpage is for users to place their cursors on an image and have a textbox appear where they can input comments. When I reached out to Stack Overflow users about the missing textbox, one individual pointed out that I had neglected to include the jQuery library link, so I made sure to add that as well.

I have meticulously checked the code structure (ensuring JavaScript and jQuery are within the head tags, while CSS is enclosed in style tags), yet the code still fails to execute. Since all scripts are client-side, I decided against using XAMPP and instead saved the files in "My Documents" and ran them in the browser, but encountered the same issue. Can someone kindly enlighten me on what mistake I might be making? If a code runs perfectly in JFiddle, why does it not function properly in a browser? This situation is perplexing.

<!DOCTYPE html>
<html>
    <head>
        <script type='text/javascript' src='//code.jquery.com/jquery-2.1.0.js'></script>
        <script>
            $('.car').click(function() {
                $('.comment').css("visibility", "hidden");
                $('#button').css("visibility", "hidden");

                var id = $(this).children('label').attr('for');
                var buttonOffset;
                switch (id) {
                    case 'mercedesbenz':
                        buttonOffset = '0';
                        break;
                    case 'porche':
                        buttonOffset = '33%';
                        break;
                    case 'bmw':
                        buttonOffset = '66%';
                        break;
                }

                $(this).children('.comment').css("visibility", "visible");
                $('#button').css("left", buttonOffset);
                $('#button').css("visibility", "visible");
            });

            $('.comment').mouseleave(function() {
                setTimeout(function() {
                    $('.comment').css("visibility", "hidden");
                    $('#button').css("visibility", "hidden");
                }, 500);
            });
        </script>
        <style>
            #form {
                position: absolute;
                overflow: hidden;
                top: 50%;
                left: 50%;
                margin-right: -50%;
                transform: translate(-50%, -50%);
            }
            .car {
                float: left;
                margin: 2% 2% 5% 2%;
            }

            .car label img {
                transform: scale(0.8);
                transition-duration: 0.2s;
            }

            .car label img:hover {
                cursor: pointer;
                transform: scale(1);
            }

            .comment {
                position: absolute;
                visibility: hidden;
            }

            .comment input {
                width: 128px;
                font-size: 1em;
            }

            .car label img {
                width: 128px;
                display: block;
            }

            #button {
                position: relative;
                left: 66%;
                margin: 2%;
                visibility: hidden;
            }
         </style>
    </head>
    <body>
        <div id="form">
            <form method="post" action="#">
                <div class="car">
                    <label for="mercedesbenz">
                        <img src="http://tinyurl.com/on964r9" />
                    </label>
                    <div class="comment">
                        <input type="text" id="mercedesbenz" placeholder="Merc" />
                    </div>
                </div>
                <div class="car">
                    <label for="porche">
                        <img src="http://tinyurl.com/on964r9" />
                    </label>
                    <div class="comment">
                        <input type="text" id="Porche" placeholder="Porc" />
                    </div>
                </div>
                <div class="car">
                    <label for="bmw">
                        <img src="http://tinyurl.com/on964r9" />
                    </label>
                    <div class="comment">
                        <input type="text" id="bmw" placeholder="Beemer" />
                    </div>
                </div>
                <input id="button" type="submit" name="submit" value="Submit">
            </form>
        </div>
    </body>
</html>

Answer №1

Your code is being executed before the DOM has finished loading. To ensure that your code runs at the correct time, you can either move it after your HTML or use $(document).ready().

For example, if you have code like this:

$('.car').click(function() {...});

The .car object does not exist in the DOM yet, so the event handler cannot be installed.

You can fix this by using:

$(document).ready(function() {
    $('.car').click(function() {...});
});

Alternatively, you can place your <script> tag just before the </body> tag to ensure that the DOM elements are loaded before your script runs:

<body>
  ... various HTML
<script>
    $('.car').click(function() {...});
</script>
</body>

It's important to note that jsFiddle defaults to running code after the DOM has loaded, which may differ from a real web page. You can control when Javascript runs on a jsFiddle using the drop-down menu in the upper left corner.

Answer №2

To ensure your JavaScript code only starts executing after the webpage has fully loaded, insert it into either window.onload or $(document).ready().

All of your JS code should be placed inside a function called doStuff();

window.onload = doStuff;
function doStuff() {
    ...
}

or

$(document).ready(doStuff);

If you encounter any issues, consider updating your 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

Finding the current week using date information from an array of objects in JavaScript

I have an array of objects with a date key, and I am trying to filter out the objects that fall within the current week. How can I achieve this and get the objects from the current week? I attempted to use the filter method, but I believe I need to forma ...

Getting the href values of dynamically changing links with Selenium in Python: A step-by-step guide

Is there a way to extract all hrefs(links) located in anchor tags using JavaScript code with Selenium Python, especially when these links are dynamically updated? The tag I am trying to click on is as follows: enter image description here I have managed t ...

Create a vertical scrollable feature for the <ul> element when it is set to flex, limiting its height within the specified dimensions

In order to enhance user experience, I have implemented a live search bar that is only visible on mobile screens. For the CSS styling: .search-results { z-index: 9999; width: 80vw; position: absolute; top: 80%; left: 10%; } .search-results li ...

Visual button spacing

There is no CSS styling applied to the page. When two image buttons are placed in separate lines of code like this: <asp:ImageButton ID="btnVoteUp" Height="16px" Width="16px" runat="server" ImageUrl="images/thumbs_up.gif" CausesValidation="false" Co ...

Is there a way to code a checkbox within a dropdown menu?

I am seeking assistance in making this dynamic I am still learning Laravel and require some guidance on how to program a checkbox within a select dropdown. Here is the HTML form I have: <div class="container w60"> <div class="row pad_y_2 ...

Javascript's second element does not trigger a click event with similar behavior

I'm currently facing an issue with displaying and hiding notification elements based on user interaction. My goal is to have multiple popup elements appear when the page loads. Then, when a user clicks the ".alert-close" element within one of the popu ...

What steps do I need to take to ensure that when running npm start, Chrome opens in incognito mode or that caching is

During my development process, I have encountered frustrating issues related to caching that are difficult to debug. I am looking for a way to disable caching in order to alleviate this problem. One approach I am considering is modifying the default beha ...

access various paths to distinct iframes

<?php // Specify the directory path, can be either absolute or relative $dirPath = "C:/xampp/htdocs/statistics/pdf/"; // Open the specified directory and check if it's opened successfully if ($handle = opendir($dirPath)) { // Keep readin ...

What is the process of invoking a function on a specific element when it is encapsulated within an if statement in Meteor.js

Here is an example: {{#if currentUser}} <li><a class="waves-effect waves-light btn modal-trigger modal-close" href="#upload">Upload Image</a></li> {{/if}} Currently, I am implementing the following: Template.MasterLayout.onRe ...

Interacting between frames with jQuery

I have main_page.htm with the following frameset structure: <frameset rows="30,*" frameborder=0 border=0> <frame name="top_frame" src="top.htm"> <frame name="bottom_frame" src="bottom.htm"> </frameset> The content in ...

What is the best way to modify this CSS code for use in a React Native

Encountering an issue while trying to apply this CSS property in a React Native project. border-radius: 50% / 100%; Attempting the following: borderRadius: '50% / 100%' An error message is displayed stating "Java.lang.string cannot be cast to ...

Customizing object joining rules in JavaScript arrays

My array consists of different colored items with their respective types and amounts [ { color: 'blue', type: '+', amount: '1' }, { color: 'blue', type: '-', amount: '1' }, { color: 'blu ...

Achieving accurate JSON output from Elasticsearch's autosuggest feature can be

Running my node.js server involves sending queries to an elasticsearch instance. I have a JSON example of the query's output: { "took": 2, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 ...

Slideshow box with images aligned perfectly

I have designed a container with images, but my goal is to: either show the images inline or stack them on top of each other, and then be able to navigate through them using jQuery. I attempted absolute positioning on both .box and .box img, as well as u ...

I could really use some assistance with this script I'm working on that involves using ($

Using Ajax for Form Submission: $.ajax({ url: 'process.php', type: 'post', data: 'loginName=' + $("#loginName").val() + 'loginPass=' + $("#loginPass").val(), dataType: 'json', success: func ...

CSS files are failing to load in ASP .NET framework

I am facing a similar issue to the one described by another user on Stack Overflow here: Asp.NET not applying my CSS files However, after adding the following code to my web.config file, nothing seems to change: <location path="css"> &l ...

Stop the stream coming from getUserMedia

After successfully channeling the stream from getUserMedia to a <video> element on the HTML page, I am able to view the video in that element. However, I have encountered an issue where if I pause the video using the controls on the video element a ...

Is there a way to identify when no rows contain specific values in PostgreSQL or node.js and return false?

Here is an example of a table: P Q t f f t f f In SQL, is there a way to return false when querying for t t, but true when querying for t f, f t, or f f? Should this be handled with node.js by first doing a select and then using if-else statements based ...

Cause: Trying to serialize an `object` that is not JSON serializable (such as a "[object Date]"). Ensure that only JSON serializable data types are returned

Currently, I am utilizing Prisma along with Next.js. My issue arises when attempting to retrieve content from Prisma within the getStaticProps function; while it successfully fetches the data, I encounter difficulties passing it on to the main component. e ...

The dimensions of my textarea and input field are different

Just starting out with HTML and CSS here. I'm trying to use flexbox to create a form, but the width of my input fields and text area is off for some reason. Any ideas on what might be missing from my code? Thanks in advance! Here's the CSS I&apo ...