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

Am I making a mistake in my implementation of sending Socket.io messages to a designated room?

Upon a user joining, I alter their ID to a shortened random code. This change is made to utilize the id as a visible session ID on the front-end. I mention this to prevent confusion regarding non-standard socket IDs and their relation to potential issues. ...

How can I retrieve the chosen value from an AJAX combobox using JavaScript in an ASP.NET C# application?

How can I retrieve the selected value from an AJAX combobox item using JavaScript in ASP.NET C#? Below is the code snippet: <asp:ComboBox ID="dropdown_dest" runat="server" Width="90%" onfocusout="blurFunction()" AutoCompleteMode="SuggestAppend" CssCla ...

Add drop caps to every individual word within a hyperlink

Is there a way to recreate the menu effect similar to using CSS fonts and drop caps for each word? I'm aware of the CSS code: p.introduction:first-letter { font-size : 300%; } that enlarges the first character of the first word, but I want this ef ...

Rendering real-time data using jQuery's Ajax functionality

Imagine having a webpage that gradually returns a large amount of data over time. Here's an example code snippet to illustrate this: <?php $iTime = time(); while(time()-$iTime < 10 ) { echo "Hello world"; echo str_repeat( ' &apos ...

Issue with Bootstrap error class not functioning in conjunction with hide class

I need to create a form that slides down two input fields when an error occurs, and I want them to have the bootstrap error class. The 'error' class works fine without the 'hide' class being present, but when the 'hide' class ...

Use Javascript or Jquery to dynamically change the background color of cells in HTML tables based on their numerical

I am working with a collection of HTML tables that contain numbers presented in a specific style: <table border="1"> <tr> <th>Day</th> <th>Time</th> <th>A</th> <th>B</th> &l ...

I'm facing a MongooseServerSelectionError: when trying to connect to 127.0.0.1:27017. Despite trying all the solutions provided on StackOverflow, the issue persists

MongooseServerSelectionError: Failed to connect to 127.0.0.1:27017 at NativeConnection.Connection.openUri (/mnt/d/Ecommerce/node_modules/mongoose/lib/connection.js:802:32) at /mnt/d/Ecommerce/node_modules/mongoose/lib/index.js:341:10 at ...

The partial template is not functioning as anticipated

Introducing an interface designed to accept two templates, with the resulting function being a partial of one of them (similar to React-Redux): export type IState<TState, TOwnProps> = { connect: (mapStateToProps: MapStateToProps<TState, Parti ...

Dragging a div element within a table

I am working on an HTML code where I need to make the colored divs draggable and fit them into specific table cells. The green div should occupy 2 cell spaces, light blue 3 cell spaces, yellow 4 cell spaces, and dark blue 5 cell spaces. While I have the d ...

What method can I use in pure Javascript to identify which day the week begins on, either Monday or Sunday, based on the

Can someone help me determine the start day of the week in local time using only Javascript? The start day could be Monday, Sunday, Saturday, or Friday. I came across this helpful resource on Stack Overflow: <firstDay day="mon" territories="001 AD AI ...

Facing the issue of "Protractor not syncing with the page" while trying to navigate an Angular website

I'm currently attempting to follow the tutorial for Protractor on the official Protractor website, but I've hit a roadblock at step 0. My setup involves using protractor and webdriver-manager version 6.0.0. I am running Linux (Ubuntu 18.06) as m ...

Identify which anchor tag from the group with the matching class was selected and retrieve its unique identifier

There are multiple anchor tags with the same class in my code. <a href='' id='id1' class='abc'>Link 1</a> <a href='' id='id2' class='abc'>Link 2</a> <a href='&apos ...

Add a preventDefault event listener to a submit button that triggers a specific function

$(function() { $('#login').submit(function(e){ preventSubmission(); e.preventDefault(); }); }); function preventSubmission() { $('#btnLogin').attr('disabled','disabled'); $("#btnLogi ...

The intended functionality of clicking on an image is exclusively reserved for its immediate parent element

I have a feature on my website that displays an image gallery. When a user clicks on an image, it opens up the image in full screen similar to Facebook's theatre mode. I have written code so that when the user clicks anywhere in the container of the i ...

Mastering the art of knowing when to implement asynchronous and synchronous programming techniques is essential for

As I explore asynchronous programming in JavaScript, I am faced with the challenge of integrating two email providers: Sendgrid and Mailgun. My goal is to send an email using one provider, and if any errors occur during the process, automatically resend th ...

Error encountered: X.setValue is not a valid function and cannot be used to set the value. However, manually inputting the value as a

When I try to use the line sseTopicString.setValue(sseValueNumber), a Type error is thrown: Uncaught TypeError: sseTopicString.setValue is not a function. Interestingly, if I output the value (string) of sseTopicString before the dot, everything works fin ...

Storing Form Input in Browser's Local Memory

I am currently working on a form section where individuals can input their email addresses. However, I have encountered a couple of issues: (1) After submitting an email address, the page refreshes. While I understand that this is inevitable without usin ...

Using ThreeJS to Apply Dual Materials to a Mesh Entity

With ThreeJS, it's possible to incorporate more than one material into an Object3D/Mesh as stated in the documentation. You can either utilize a single Material or an array of Material: Class declaration and constructor for Mesh TypeScript file (exce ...

Having trouble with your contact form and not getting it to work properly with Javascript, Ajax, or

I've been struggling to get a contact form working for an entire day. I included the following script at the top of my page: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> This is the structure ...

passing a PHP variable into an HTML input field

Recently, I've encountered a problem where I need to transfer PHP variables to HTML input fields. echo $ManuellTagnavnMain; for ($n = 0; $n < 6; $n++) { print_r(++$ManuellTagnavnMain.PHP_EOL); } I'm looking for a way to pass these values ...