Script for collapsing or expanding is non-functional

Although I am a beginner in Javascript coding, I am eager to learn more about it.

I stumbled upon some tutorials on creating collapse/expand <div> blocks. After testing the code on jsfiddle, I found that it works fine there. You can find the code here

Unfortunately, I'm facing an issue where the code doesn't work on my live website.

Initially, I inserted all the Javascript and HTML code in the WordPress Page editor. Later on, I moved the Javascript to the header. I suspect that the source of the code might be causing the problem, but I'm not entirely sure.

Below is the snippet of Javascript code I inserted in the header.php:

<script type="text/javascript" language="javascript" src="http://example.com/wp-content/themes/crimson/scripts/jquery.min.js">
function toggle2(showHideDiv, switchTextDiv) {
    var ele = document.getElementById(showHideDiv);
    var text = document.getElementById(switchTextDiv);
    if (ele.style.display == "block") {
        ele.style.display = "none";
        text.innerHTML = "expand";
    }
    else {
        ele.style.display = "block";
        text.innerHTML = "collapse";
    }
}

function toggle3(contentDiv, controlDiv) {
    if (contentDiv.constructor == Array) {
        for (i = 0; i < contentDiv.length; i++) {
            toggle2(contentDiv[i], controlDiv[i]);
        }
    }
    else {
        toggle2(contentDiv, controlDiv);
    }
}​
</script>​​​​​​​​​​​​​​​​

The HTML code remains the same as the one in the fiddle HTML panel and it is displayed on a WordPress page.

I would appreciate any insights on what could be wrong with this code. Could it be related to the source of the javascript code?

Upon checking the Chrome console, I received the following error message:

Uncaught ReferenceError: toggle2 is not defined example.com:103 onclick

The main question that puzzles me is why the code functions correctly on jsfiddle using either mootools or jquery frameworks, but fails to work on the live site?

UPDATE: I have made adjustments to the script tags, however, the issue persists.

Answer №1

Ensure that your Javascript code is enclosed in its own tags.

  <script type="text/javascript" language="javascript" src="http://example.com/wp-content/themes/crimson/scripts/jquery.min.js">
  <script type="text/javascript">

       INSERT YOUR CODE HERE

  </script>

If you are utilizing jQuery, remember to incorporate the ready() function like so:

       $(function(){
             INSERT YOUR CODE HERE
       });

  <a href="#" id="clickme">Click</a>  
  <div id="d1">Some content to hide</div>

In the head section:

  <script type="text/javascript">
       $(document).ready(function(){
           $("#clickme").toggle(function(){
               $("#d1").show();
           },
             function(){
                $("#d1").hide();
             }
           );
       });
  </script>

Remember to retain the reference to jQuery in your code.

Answer №2

There are a few issues to address:

  • An overlapping script tag
  • Mixing Mootools and jQuery in different parts of the code
  • Loading jQuery but using plain Javascript for animations

To fix this, make sure to correct the script tags:

<script type="text/javascript" language="javascript" src="http://example.com/wp-content/themes/crimson/scripts/jquery.min.js"></script>
<script type="text/javascript">
function toggle2(showHideDiv, switchTextDiv) {
    var ele = document.getElementById(showHideDiv);
    var text = document.getElementById(switchTextDiv);
    if (ele.style.display == "block") {
        ele.style.display = "none";
        text.innerHTML = "expand";
    }
    else {
        ele.style.display = "block";
        text.innerHTML = "collapse";
    }
}

function toggle3(contentDiv, controlDiv) {
    if (contentDiv.constructor == Array) {
        for (i = 0; i < contentDiv.length; i++) {
            toggle2(contentDiv[i], controlDiv[i]);
        }
    }
    else {
        toggle2(contentDiv, controlDiv);
    }
}​
</script>

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

Learn how to swap out the traditional "back to top" button with a customized image and make it slide onto or off the page instead of simply fading in and out

As a newcomer, I am trying to replicate a unique "back to top" effect that caught my eye on another website. Instead of the traditional fade-in approach when scrolling down, the "back to top" image in question elegantly slides out from the bottom right c ...

Parsing text files with Highcharts

As a beginner in JavaScript and HighCharts, I am facing a simple problem that has me completely lost. My goal is to generate a scatter chart with three lines by reading data from a text file formatted like this: x y1 y2 y3 1.02 1.00 6.70 ...

Showing scheduled activities from a database on an AngularJS mwl calendar

How can I modify my code to display events from a database on an mwl calendar based on the saved date rather than showing all events for today only? I want to show events based on the notifyDate field in the database. Can someone help me with this? html ...

Error Message "Alexa.create is not a valid function" encountered while using the Alexa HTML Web API on the Echo Show 10

Here is the HTML code for my custom Alexa Skill. <head> <script src="https://cdn.myalexaskills.com/latest/alexa-html.js"> </script> </head> <body> var alexaClient; Alexa.create({version: '1.0'}) .t ...

Tips for implementing a button redirection to a different page using React

I am facing an issue with a component that includes a function onClick in its Class.propTypes: onClick: PropTypes.func Within another component, I have used this particular component multiple times to populate a page. Each instance of these components con ...

ReactJS: error occurs when trying to fetch data and encountering issues with reading properties

I am currently attempting to initiate an API call (a GET request) in order to download a document. However, I am encountering an error when making the API call: TypeError: Cannot read properties of undefined (reading 'payload') const printPin ...

Presentation comparing ng-show and ng-hide efficiency

Introduction:- There may be some who opt to use ng-show instead of ng-hide="!true", while others choose ng-hide over ng-show="!true". Technically, the ng-hide directive is not necessary. However, Angular introduced it for a standard coding structure. Plea ...

Error: react/js encountered an unexpected token

While attempting to execute my project, I encountered an error in the console related to a function within the code. The exact error message reads as follows: "63:25 error Parsing error: Unexpected token, expected (function toggleDrawer = (open) => () ...

Validation of date format in AngularJS when using the input type date

Attempting to generate a date using AngularJS, following the provided documentation. Input with date validation and transformation. If the browser does not support HTML5 date input, a text element will be used instead. In this scenario, text should ...

Initiate an AJAX call with various data formats included

I am currently developing an application that allows users to input values through an interface and send AJAX requests (similar to a REST API). My question pertains to sending data of multiple types in a single request. For example, here is a scenario: F ...

Guide to Generating Downloadable Links for JPG Images Stored in MongoDB Using Node.js

I have successfully uploaded an image to MongoDB as a Buffer. Now, I need to figure out how to display this image in my React Native app using a URL, for example: http://localhost:8080/fullImg.jpeg How can I achieve this? Below is the MongoDB Schema I am ...

Creating new components within A-frame

I've been attempting to implement the bubble function into my scene to generate a sphere, but unfortunately nothing is showing up. Even when I try creating a sphere without using the bubble function, it still doesn't appear in the scene. func ...

What is the best way to ensure that the maximum price is mandatory when entering a minimum price?

Essentially, the process works like this: if a person inputs a minimum price but forgets to input a maximum price, then presses search, it will not perform the search and a message will appear next to the max price field reminding them to enter a maximum ...

Ensure that a select input, dynamically generated, is marked as 'required' only when other inputs have been filled out

Displayed below is a snapshot of a page I'm developing that allows users to input details about various rooms in a property. Users have the ability to 'add' multiple rooms, triggering javascript/jQuery to dynamically create additional input ...

What is the best way to access and display the innerText of elements that have been removed using console

When I call the updateCartTotal() function, my goal is to display in the console the items that have been removed from the shopping cart. Every time I click on the remove button, I want it to show the item and the price. However, instead of displaying the ...

Navigate through the Jquery slider by continuously scrolling to the right or simply clicking

Is there a way to prevent my slider from continuously scrolling? I think it has something to do with the offset parameter but I'm having trouble figuring it out. Any assistance would be greatly appreciated. var $container = $(container); var resizeF ...

Obtaining an XML element within an XSLT transformation

I need to retrieve the value of an XML element within XSL. Although my JavaScript is able to select one XML document, there are elements in other documents that I also require. I am uncertain if this task is feasible or if my syntax is incorrect. This is ...

Create a filter system using a MERN stack that incorporates regex, a search box,

In an effort to understand how the MERN stack operates as a cohesive unit, I have taken on a hands-on approach by following tutorials from bezcoder. These include guides on Node.js/Express/MongoDb (Github entire code) and Reactjs (Github entire code). Sam ...

Is there a way to determine the number of syllables in text as it is being typed?

Working on a React-based web app, I am trying to determine the number of syllables in a textarea as the user types. Encountering errors like "cannot find length of a null" at every turn. Right now, all I want is to utilize console.log() for troubleshooti ...

AngularJS written plugin in Javascript

I developed an app using Rails and AngularJS. A startup has reached out to me about transferring the technology to their website, but they have limited tech resources. The goal is to create a seamless integration process. The idea is to make it similar to ...