JS Code from a JS Fiddle failing to run in a web browser examination

I have been experimenting with a fantastic Expand/Collapse JavaScript function that I came across on JS Fiddle, but unfortunately, it's not working as expected when testing it in a browser. Can anyone provide some guidance on what might be causing the issue?

I'm relatively new to Javascript, so any assistance would be greatly appreciated. Thank you for taking the time to help me out.

Below is the code setup that I currently have:

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<link rel="stylesheet" href="css/teststyle.css">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="expandcollapse.js"></script>
</head>

<body>

<div class="container">
    <div class="header"><span>Expand</span>

    </div>
    <div class="content">
        <ul>
            <li>This is just some random content.</li>
            <li>This is just some random content.</li>
            <li>This is just some random content.</li>
            <li>This is just some random content.</li>
        </ul>
    </div>
</div>
</body>
</html>

CSS

@charset "utf-8";
/* CSS Document */

.container {
    width:100%;
    border:1px solid #d3d3d3;
}
.container div {
    width:100%;
}
.container .header {
    background-color:#d3d3d3;
    padding: 2px;
    cursor: pointer;
    font-weight: bold;
}
.container .content {
    display: none;
    padding : 5px;
}

JS

// JavaScript Document

$(document.ready()());
    $(".header").click(function () {

    $header = $(this);
    //getting the next element
    $content = $header.next();
    //open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
    $content.slideToggle(500, function () {
        //execute this after slideToggle is done
        //change text of header based on visibility of content div
        $header.text(function () {
            //change text based on condition
            return $content.is(":visible") ? "Collapse" : "Expand";
        });
    });

});

Answer №1

Make sure to update your JavaScript call to $(document).ready. Here is the revised code:

$(document).ready(function () {
    $(".header").click(function () {
        $header = $(this);
        //Retrieve the next element
        $content = $header.next();
        //Toggle the slide of the content - slide up if visible, slide down if not.
        $content.slideToggle(500, function () {
            //Execute this after slideToggle is complete
            //Update header text based on visibility of content div
            $header.text(function () {
                //Update text conditionally
                return $content.is(":visible") ? "Collapse" : "Expand";
            });
        }); rantFormViewModel.wireEvents();
    });
});

By making these changes, everything should function as desired.

Answer №2

Your implementation of the "document.ready" function is incorrect.

Here's the proper way to do it:

$(document).ready(function() {
     // Your code goes here
});

Alternatively, you can use a simpler approach (like the example below):

$(function() {
    // Your code goes here
});

I recommend updating your Javascript file with this revised version:

$(function() {
    $(".header").click(function () {
        $header = $(this);

        // Get the next element
        $content = $header.next();

        // Toggle the slide - slide up if visible, slide down if not
        $content.slideToggle(500, function () {
            // Execute this after the slideToggle is done
            // Change text of header based on visibility of content div
            $header.text(function () {
                // Change text based on condition
                return $content.is(":visible") ? "Collapse" : "Expand";
            });
        });
    });
});

Answer №3

Your document ready function was not called or nested correctly. Here is a revised version to try:

$(document).ready(function() {
  $(".header").click(function () {

    $header = $(this);
    //get the next element
    $content = $header.next();
    //toggle the slide - slide up if visible, slide down if not
    $content.slideToggle(500, function () {
        //execute after slideToggle completes
        //change header text based on content visibility
        $header.text(function () {
            return $content.is(":visible") ? "Collapse" : "Expand";
        });
    });

  });
});

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

Is it possible to send an array value from JavaScript Ajax to PHP and then successfully retrieve and read it?

As a newcomer to PHP, I am facing a challenge in saving multiple values that increase dynamically. I'm passing an array value using the following method from my JavaScript code. $(".dyimei").each(function(i,value){ if($(this).val()=="") ...

Monitor the output of a spawned process that is currently in a state of awaiting user input

In my Swift program, I am logging information to the stdout while waiting for a termination signal of \n. The input is requested immediately upon starting and the info is logged 1~2 seconds later: fetchAndLogDataInBackground(); // will print some dat ...

Tips for automating the execution of Chrome extension code on pages with infinite scrolling

Creating my debut Chrome extension, I'm developing a tool to substitute text on web pages. The current code effectively operates on content loaded by DOMContentLoaded. However, when pages employ infinite scrolling and new content is added, the text r ...

Automatically capitalize editable input fields

I am currently implementing Jeditable in my datatable and I would like to automatically capitalize text input entries on the form. Is there a way to convert each character to uppercase if it is lowercase? I have some code that I've been working with, ...

JQuery 1.9 Javascript file contains a broken link with the path "/a"

During a security audit of our project, we discovered a vulnerability related to a broken link "/a". After thoroughly searching our project, we pinpointed the issue to a link in the JQuery-1.9.js JavaScript file that is being utilized. Within the JQuery- ...

Creating dynamic routes with Nuxt3

Within my nuxt.config.ts file, I have the ability to generate multiple routes using the following code: export default defineNuxtConfig({ generate: { routes: ['/products/1', '/products/2'] }, }) After running nuxt generate, thi ...

Tips for showcasing the complete image within v-parallax

For my project, I decided to go with vuetify as the frontend framework. It's a great choice! Now, I have a question about v-parallax - how can I make it display the full image without cropping? Below is some code snippet, and you can find the full cod ...

How to Retrieve the Index of a Value within an Array in VUE.js

I am facing an issue where I want to update the status of tasks based on a certain method call. However, the challenge lies in obtaining the index of the specific item within the array in order to modify its status. Here is my HTML setup: <div class="m ...

Loading CSS files conditionally in Angular2's index.html

Currently, my index.html page features a dark theme: <base href="/"> <html> <head> <title>XXX</title> </head> <body> <link rel="stylesheet" type="text/css" href="assets/dark_room.css"> <my-app ...

Is it possible for jQuery AJAX to function across various servers?

While working on my local server (MAMP) everything was running smoothly. But once I transferred my web application to a different server, I encountered an issue where the request wasn't working and returned the error: function() { console.log("oh no") ...

NPM encountered difficulties in resolving the dependency tree

I seem to be encountering a persistent issue that I cannot resolve on my own. My attempt to update webpack and webpack-cli in a project has been met with repeated errors of this nature: npm install webpack@latest --save-dev npm ERR! code ERESOLVE npm E ...

Mongoose virtual population allows you to fetch related fields

When attempting to utilize virtual populate between two models that I've created, the goal is to retrieve all reviews with the tour id and display them alongside the corresponding tour. This is achieved by using query findById() to specifically show o ...

Caution: Exercise caution when rendering components in React due to unstable_flushDiscreteUpdates

Trying to utilize map to render a component, but encountering a warning: Warning: unstable_flushDiscreteUpdates: Cannot flush updates when React is already rendering. MyBooks.js import React, { useState, useEffect } from 'react'; import Action ...

Incorporating Blank Class into HTML Tag with Modernizr

Currently, I am experimenting with Modernizr for the first time and facing some challenges in adding a class to the HTML tag as per the documentation. To check compatibility for the CSS Object Fit property, I used Modernizr's build feature to create ...

How to dynamically generate data with exceljs

Currently, I am attempting to download JSON data into an Excel spreadsheet. One of my requirements is to insert an image in cell a1 and then bold the headers. The code snippet below was sourced from Google; however, I need to populate the data dynamically ...

The positioning of jQuery UI elements seems to be off

I'm having an issue with the positioning of a dropdown box under its button using the jQuery UI position function. The dropdown box is not aligning correctly. Check out the fiddle for reference. $(".dropDown .dialogueBox").position({ my: " ...

How is it possible to access a variable in a function that hasn't been declared until later?

While working on a Dialog component, I had an unexpected realization. export const alert = (content: string) => { const buttons = [<button onClick={()=>closeModal()}>ok</button>] // seems alright // const buttons = [<button onCli ...

Tips for implementing a CSS override for a block element's relative date

I am looking to customize this source code by using a CSS override to ensure that the "lightning-relative-date-time" element is not utilized. I want to keep it displaying the timestamp information by default. Can you guide me on how to achieve this throu ...

Arranging shapes for varying levels of magnification

Seeking assistance with properly aligning two forms. I have tried using a positioning approach, but the layout gets disrupted when the browser's Zoom level is adjusted. The second button ends up shifting slightly either upwards or downwards. Here is t ...

Utilize dynamic CSS application within an Angular application

In my Angular application, I dynamically load URLs inside an iframe and want to apply custom.css to the loaded URL once it's inside the iframe. I attempted using ng-init with angular-css-injector function in the iframe, but the CSS is not being applie ...