Edwin Shepherd
Edwin Shepherd

Reputation: 453

JS accordions not opening

I have a website with some JS accordions on it, they do not open, however they do on codepen. I have looked in the console on chrome and I go no error messages. However when I looked in the console in Firefox I get the following error message 7 times:

HTTP "Content-Type" of "text/html" is not supported. Load of media resource http://xurbia.tk/alpha/homebeta.html failed. homebeta.html

All candidate resources failed to load. Media load paused. homebeta.html

I have no idea what is going on here so any help is much appreciated.

The relevant code for one of the accordions is as follows:

<dt>
  <a href="#accordion2" aria-expanded="false" aria-controls="accordion2" class="accordion-title accordionTitle js-accordionTrigger">
    <img src="http://xurbia.tk/alpha/pictures/Play_button_next_stop_music_pause.png" height=40px class="pull-left"/>
    Detox
    <img src="http://xurbia.tk/alpha/pictures/Play_button_next_stop_music_pause.png" height=40px class="pull-right"/></a>
</dt>
<dd class="accordion-content accordionItem is-collapsed" id="accordion2" aria-hidden="true">
  <img src="http://xurbia.tk/alpha/pictures/accordian%20pictures/Detox.PNG" width="100%" height="100%" />
  <audio controls>
    <source src="" type="audio/wav" width="100%">
      Your browser does not support the audio element.
  </audio>
</dd>

The full code can be found here: http://xurbia.tk/alpha/Stackoverflow.txt

Here is the code-pen where I started making the accordions: http://codepen.io/shardros/pen/OyJqzj

Here is the website that they do not work on: http://xurbia.tk/alpha/homebeta.html

Upvotes: 2

Views: 93

Answers (2)

Alvin Pascoe
Alvin Pascoe

Reputation: 1209

On the live site, your JavaScript is written using the module pattern...which is good.

This pattern uses an immediately invoked function expression (https://en.wikipedia.org/wiki/Immediately-invoked_function_expression).

This means that as soon as the function is declared, it is invoked (and executes).

Because you have this script in the <head> section of your page, it executes before the DOM has loaded (before your actual page loads).

This means that your JavaScript tries to add event listeners and manipulate elements that do not yet exist!

In order to fix this, move the <script> tag out of <head> and place it as the last element within the <body> tag.

This will have the effect of the JavaScript being invoked after all necessary elements have been created.

(Your example works in Codepen because they execute the JavaScript after the DOM has loaded)

Upvotes: 2

Jackson
Jackson

Reputation: 3518

Your problem is that your JS is executing before the page is loaded. It's good practice to insert your JS at the end of the <body> element to improve page load speed.

You could also use an event to fire after the page loads like this:

window.onload = function(){
    //Page has loaded
}

Upvotes: 1

Related Questions