What could be causing this code to malfunction on jsfiddle?

Why doesn't this code from W3schools work on jsfiddle? I tried to implement it here: https://jsfiddle.net/u6qdfw5f/

    <!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<body>

<div class="w3-container">
<h2>Accordions</h2>
<p>An accordion is used to show (and hide) content that is broken into sections:</p>

<div class="w3-accordion w3-light-grey">
    <button onclick="myFunction('Demo1')" class="w3-btn-block w3-left-align w3-show">Open Section 1</button>
    <div id="Demo1" class="w3-accordion-content w3-container w3-show">
    <h4>Section 1</h4>
    <p>Some text..</p>
    </div> 
    <button onclick="myFunction('Demo2')" class="w3-btn-block w3-left-align w3-show">Open Section 2</button>
    <div id="Demo2" class="w3-accordion-content w3-container w3-show">
    <h4>Section 2</h4>
    <p>Some other text..</p>
    </div>
</div>
</div>

<script>
function myFunction(id) {
    var x = document.getElementById(id);
    if (x.className.indexOf("w3-show") == -1) {
        x.className += " w3-show";
    } else { 
        x.className = x.className.replace(" w3-show", "");
    }
}
</script>

</body>
</html>

Answer №1

The issue stems from the failure of the CSS to load properly. By checking the console, an error message such as

GET https://www.w3schools.com/lib/w3.css net::ERR_INSECURE_RESPONSE
is displayed. To resolve this, add the CSS in the top right section of the fiddle.

This problem arises because the link contains https, while the w3schools website lacks a secure certificate. Trying to access

https://www.w3schools.com/lib/w3.css
on the browser will result in a privacy error. Changing it to http instead of https will make it functional in the browser.

HTTP files do not function in jsfiddle HTTPS due to security concerns. The console will display an error like:

Mixed Content: The page at 'https://jsfiddle.net/u6qdfw5f/1/' was loaded over HTTPS, but requested an insecure stylesheet 'http://www.w3schools.com/lib/w3.css'. This request has been blocked; the content must be served over HTTPS.

I've also set the javascript load type to No wrap - in <head> from the options dropdown, rather than keeping it default with onLoad. Failing to do so would lead to an error message like

Uncaught ReferenceError: myFunction is not defined
.

Check out the updated version on FIDDLE.

Answer №2

The reason your JS code isn't functioning properly is because you have set the 'Load type' in settings to execute when document.ready fires. As a result, the myFunction() definition is not within scope of the calling onclick attribute.

Another issue is that the file path for w3.css in the external files list is incorrect. By using https://, the request fails since W3Schools doesn't have an SSL certificate. It's recommended to use a http:// link instead.

After making these adjustments, the code should work successfully: Updated fiddle

However, keep in mind that the code in the W3Schools example may be a bit outdated. For modern best practices, consider utilizing unobtrusive event handlers over on* attributes and incorporating the classList to toggle classes without needing an if statement. Here's an updated version:

document.querySelectorAll('.w3-btn-block').forEach(function(el) {
  el.addEventListener('click', function() {
    var x = document.getElementById(this.dataset.target);
    x.classList.toggle('w3-show');
  })
})
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css" />

<div class="w3-accordion w3-light-grey">
  <button data-target="Demo1" class="w3-btn-block w3-left-align">
    Open Section 1
  </button>
  <div id="Demo1" class="w3-accordion-content w3-container">
    <p>Some text..</p>
  </div>
  <button data-target="Demo2" class="w3-btn-block w3-left-align">
    Open Section 2
  </button>
  <div id="Demo2" class="w3-accordion-content w3-container">
    <p>Some text..</p>
  </div>
</div>

Alternatively, if you're familiar with jQuery as per your tag on the question, you could opt for this approach:

$('.w3-btn-block').click(function() {
  var x = $(this.dataset.target);
  x.toggleClass('w3-show');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css" />

<div class="w3-accordion w3-light-grey">
  <button data-target="#Demo1" class="w3-btn-block w3-left-align">
    Open Section 1
  </button>
  <div id="Demo1" class="w3-accordion-content w3-container">
    <p>Some text..</p>
  </div>
  <button data-target="#Demo2" class="w3-btn-block w3-left-align">
    Open Section 2
  </button>
  <div id="Demo2" class="w3-accordion-content w3-container">
    <p>Some text..</p>
  </div>
</div>

It's advised to avoid using W3Schools as a reference, considering their tutorials tend to be outdated and occasionally provide inaccurate information. For JavaScript guidance, refer to Mozilla Developer Network (MDN), and utilize the official documentation for jQuery.

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

Tips for wrapping text to fit the width of a column

Hello, I have a table with varying column widths as shown below ${"#goldBarList"} table tr td:first-child{width:5%;} ${"#goldBarList"} table tr td:first-child+td{width:5%;} ${"#goldBarList"} table tr td:first-child+td+td{width:6%;} ${"#goldBarList"} table ...

Is there a method available to condense or merge PHP, DHTML, and JavaScript components efficiently?

The title may be a bit confusing, so let me explain my idea here: Imagine we have a component for a web page, such as a database-driven table or grid. This hypothetical "component" functions independently, relying on several mixed language files: HTML for ...

Exploring Parameters to Customize Search Results in React

I am currently working on implementing a data filtering system based on user input. However, it seems that the data disappears whenever I enter something into the search box. Upon inspecting the dev tools, I can see that the query state is being saved pro ...

Error encountered: The Jquery-ui functionality ceases to operate upon the completion of content

I'm utilizing the jQuery UI library to rearrange the items on my list. Initially, everything works smoothly without any issues. However, when I navigate to another page and then return to the page with my list, I encounter difficulties. It's wor ...

`Express.js Controllers: The Key to Context Binding`

I'm currently working on a project in Express.js that involves a UserController class with methods like getAllUsers and findUserById. When using these methods in my User router, I have to bind each method when creating an instance of the UserControlle ...

The onBlur event attached to a div is triggered when transitioning from one input element to another within the same div

Here's a scenario: I have a div with two input fields nested inside, like this: <div> <input placeholder="Input1"/> <input placeholder="Input2"/> </div> I have a requirement to trigger a specific ...

Sending URL parameters from a React frontend to an Express API call involves crafting the request URL with

I'm currently working on a project where I need to make a fetch request from React to Express. The API URL requires parameters, but I want the last part of the URL to be dynamic. How can I pass a parameter from React to the Express API URL? Here' ...

Tips for successfully sending parameters in a Google Geocoding request

Dealing with an array of objects containing addresses, each with four fields. The first field is the current location (store), while the others provide address information. The challenge is ensuring that I end up with a result in the format key:value (sto ...

Ensure the footer remains fixed while scrolling

For the past day, I've been tackling a challenge with my online shop project. On the specific item's page, I want to include a fixed [add to cart] button as a footer initially, which then becomes sticky when scrolling to a certain point. You can ...

Surrounding the text with background color

My H1 text is in a div that spans multiple lines due to the fixed width of the div. I am looking to set the background color to only appear behind the actual text of the H1, without extending into empty space at the end of each line. In addition, I also n ...

What is the best way to retrieve data from an Express endpoint within a React component?

I am working on integrating a React component with an Express endpoint that returns the string "sample data". The goal is to call this endpoint from my React app, store the text in state, and then display it on the screen. Here is my component: class App ...

Utilize localstorage with Redux and Next.js to initialize the state

Having an issue when attempting to populate the initial state from local storage in order to create a store. I encountered the following error message: ReferenceError: localStorage is not defined Here is my store configuration: const store = createStore(r ...

Regular expression for matching zero's following a decimal

I'm currently working on a regex method to validate decimals that only allow 2 numbers after the decimal point. For example, it should return true for 1.00 and false for 1.000, which it currently does. However, I also want it to return false for value ...

What is the best way to customize the text in the navigation bar at the top of the page

I'm having trouble with the Navigation Bar code in my header. The text is not staying within the header and I can't seem to fix it. Is there a CSS solution to keep the text contained within the header? <div class="header"> <img src= ...

Steps to switch the displayed ionicon when the menu is toggled

My goal is to display the 'menu-outline' ionicon on my website until it is clicked, at which point the icon will change to 'close-outline' and vice versa. I am utilizing jQuery for this functionality. Although I am aware of how to togg ...

Unable to display canvas background image upon webpage loading

Currently working on a JavaScript project to create a captcha display on a canvas. The issue I'm facing is that the background image does not load when the page initially opens. However, upon hitting the refresh button, it functions as intended. Here& ...

JavaScript function returning code

I am trying to create a JavaScript object with multiple functions, but I keep encountering an exception undefined is not a function Here is my JS code: var Cars = null; $(function () { Cars = function() { return { ...

Using vue.js to customize the items shown in the ox carousel

Greetings, I am currently utilizing the "carousel" component from Buefy with Vue.js. In desktop resolution, I need to display 3 elements, but on mobile devices, I want only one article to be visible. I have created a function that adjusts the property of t ...

what is the easiest way to retrieve JSON data by referring to HTML values using jQuery?

Although I am new to jquery, I am determined to complete my project. Seeking assistance from experienced individuals. My goal is to code the following HTML structure: <li value="bca"></li> <li value="bni"></li> <li value="bri"& ...

Node/Express API returning empty body when being accessed through fetch or axios requests

Currently working on integrating an API call in a React app using Node/Express. No matter where I place the fetch/axios call, the parsed body always shows up as undefined in my controller. Yesterday, I was experimenting with fetch but decided to switch to ...