Gera Gera - 7 months ago 8
HTML Question

Something is stopping JavaScript from running when I try to add text effect 'accordion' in a html document

I'm trying to implement this simple text accordion effect but it's not working...Something is 'blocking' the JavaScript code...If I create a simple html page with the same code (copy & paste) it's working but if I try to implement this accordion effect to another html page with previous content (a simple html menu and some JavaScript variables). When I click on the button...nothing changes and the previous JavaScript code is not working neither...So if I mix all JavaScript code, Nothing works but I don't know why.

If you try to execute the code, maybe you'll get an error because of this line:

var textRecovered = localStorage.getItem("storedText");
It works in my machine but you don't have the variable storedText on your localStorage so you can skip it. But I don't know if I mix it with accordion JavaScript effect stops working.

The logic (goal) is as follows: From page A I store
storedText
variable using localStorage, on page B. Then I recover the value of that variable (text Array). What I want to do is show that text as a list using the accordion effect to better organize the text, but the accordion effect or any JavaScript code does not work.

Maybe I should consider using jQuery or JavaScript functions ... I'm lost.

Page 'B' code:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" lang="es-es">
<link rel="stylesheet" href="css/layout.css" type="text/css" media="screen">
<link rel="stylesheet" href="css/menu.css" type="text/css" media="screen">
<link rel="stylesheet" href="css/accordion.css" type="text/css" media="screen">
<script src="myscripts.js"></script>



</head>
<body>
<!--Añadimos al area principal el efecto acordeon con el texto -->
<div id="mainArea">
<button class="accordion">Section 1</button>
<div id="placeholder" class="panelacc"></div>

<button class="accordion">Section 2</button>
<div class="panelacc">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<button class="accordion">Section 3</button>
<div id="foo" class="panelacc">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</div>

<!-- MENU -->
<div class="container">
<ul id="nav">
<li><a href="#"><img src="images/t1.png" /> Dashboard</a></li>
<li><a href="#" class="sub" tabindex="1"><img src="images/t2.png" />Reporting</a><img src="images/up.gif" alt="" />
<ul>
<li><a href="llog.html"><img src="images/empty.gif" />LYNIS LOG</a></li>
<li><a href="#"><img src="images/empty.gif" />LYNIS REPORT</a></li>
</ul>
</li>
<li><a href="#" class="sub" tabindex="1"><img src="images/t3.png" />Lynis Tests</a><img src="images/up.gif" alt="" />
<ul>
<li><a href="#"><img src="images/empty.gif" />Accounting</a></li>
<li><a href="#"><img src="images/empty.gif" />Authentication</a></li>
<li><a href="#"><img src="images/empty.gif" />Banner</a></li>
<li><a href="#"><img src="images/empty.gif" />Boot</a></li>
<li><a href="#"><img src="images/empty.gif" />Crypto</a></li>
<li><a href="#"><img src="images/empty.gif" />File Integrity</a></li>
<li><a href="#"><img src="images/empty.gif" />Firewall</a></li>
<li><a href="#"><img src="images/empty.gif" />Hardening</a></li>
<li><a href="#"><img src="images/empty.gif" />Kernel</a></li>
<li><a href="#"><img src="images/empty.gif" />Logging</a></li>
<li><a href="#"><img src="images/empty.gif" />Mail</a></li>
<li><a href="#"><img src="images/empty.gif" />Malware</a></li>
<li><a href="#"><img src="images/empty.gif" />Nameservers</a></li>
<li><a href="#"><img src="images/empty.gif" />Networking</a></li>
<li><a href="#"><img src="images/empty.gif" />PHP</a></li>
<li><a href="#"><img src="images/empty.gif" />Printing</a></li>
<li><a href="#"><img src="images/empty.gif" />Processes</a></li>
<li><a href="#"><img src="images/empty.gif" />Shell</a></li>
<li><a href="#"><img src="images/empty.gif" />Software</a></li>
<li><a href="#"><img src="images/empty.gif" />Squid</a></li>
<li><a href="#"><img src="images/empty.gif" />SSH</a></li>
<li><a href="#"><img src="images/empty.gif" />Storage</a></li>
<li><a href="#"><img src="images/empty.gif" />Time</a></li>
<li><a href="#"><img src="images/empty.gif" />Tooling</a></li>
<li><a href="#"><img src="images/empty.gif" />Web</a></li>
</ul>
</li>
<li><a href="#"><img src="images/t2.png" />Overview</a></li>
</ul>
</div>
<!-- END MENU -->

</body>
</html>


myscript.js code:

/*Recuperamos la variable almacenada en local storage y una vez guardado en una variable vaciamos el contenido de localstorage */
var textRecovered = localStorage.getItem("storedText");
var lines = textRecovered.split("\n");
window.localStorage.clear();
for (var i = 0; i < lines.length; i++) {
console.log(lines[i]);
}

/* Script que nos permite gestionar los eventos para el texto en forma de acordeon */


var acc = document.getElementsByClassName("accordion");

for (var j = 0; j < acc.length; j++) {
acc[j].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}

// selects the div with an id of placeholder
var div = document.getElementById('placeholder');


var fruits = ['I want a link <a href="http://google.com">here</a>','I want a link here','I want a link here','I want a link here','I want a link here'],
ul = document.createElement('ul'); // create an arbitrary ul element

// loop through the fruits array
for(var i in fruits) {
// create an arbitrary li element
var li = document.createElement('li'),
content = document.createTextNode(fruits[i]); // create a textnode to the document
var link = "http://google.com";
var element = document.createElement("span");
element.innerHTML = fruits[i];
li.appendChild(element); // append the created textnode above to the li element
ul.appendChild(li); // append the created li element above to the ul element
}
div.appendChild(ul); // finally the ul element to the div with an id of placeholder


All CSS code together:

button.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}

button.accordion.active, button.accordion:hover {
background-color: #ddd;
}

button.accordion:after {
content: '\02795';
font-size: 13px;
color: #777;
float: right;
margin-left: 5px;
}

button.accordion.active:after {
content: "\2796";
}

div.panelacc {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: 0.6s ease-in-out;
opacity: 0;
}

div.panelacc.show {
opacity: 1;
max-height: 500px;
}

div.panelacc.show p {
color: black;
}

*{
margin:0;
padding:0;
}

body {
background-color:#bababa;
}

div#fileOutput{
margin: auto;
margin-top: 50px;
margin-left: 250px;
margin-right: 50px;
margin-bottom: 50px;
width: 960px;
height: 800px;
white-space: pre-line;
border: solid 1px black;
padding: 5px;
}

input[type="file"]{
margin: auto;
width: 960px;
height: 50px;
margin-left: 250px;
white-space: pre-line;
border: solid 1px black;
padding: 5px;

}


div#mainArea{
margin: auto;
margin-top: 50px;
margin-left: 250px;
margin-right: 50px;
margin-bottom: 50px;
width: 960px;
height: 800px;
white-space: pre-line;
border: solid 1px black;
padding: 5px;
}

#nav {
border:3px solid #3e4547;
box-shadow:2px 2px 8px #000000;
border-radius:3px;
-moz-border-radius:3px;
-webkit-border-radius:3px;
position: fixed;
top: 0; left: 0;
}
#nav, #nav ul {
list-style:none;
padding:0;
width:200px;
}
#nav ul {
position:relative;
z-index:-1;
}
#nav li {
position:relative;
z-index:100;
}
#nav ul li {
margin-top:-23px;

-moz-transition: 0.4s linear 0.4s;
-ms-transition: 0.4s linear 0.4s;
-o-transition: 0.4s linear 0.4s;
-webkit-transition: 0.4s linear 0.4s;
transition: 0.4s linear 0.4s;
}
#nav li a {
background-color:#d4d5d8;
color:#000;
display:block;
font-size:12px;
font-weight:bold;
line-height:28px;
outline:0;
padding-left:15px;
text-decoration:none;
}
#nav li a.sub {
background:#d4d5d8 url("../images/down.gif") no-repeat;
}
#nav li a + img {
cursor:pointer;
display:none;
height:28px;
left:0;
position:absolute;
top:0;
width:200px;
}
#nav li a img {
border-width:0px;
height:24px;
line-height:28px;
margin-right:8px;
vertical-align:middle;
width:24px;
}
#nav li a:hover {
background-color:#bcbdc1;
}
#nav ul li a {
background-color:#eee;
border-bottom:1px solid #ccc;
color:#000;
font-size:11px;
line-height:22px;
}
#nav ul li a:hover {
background-color:#ddd;
color:#444;
}
#nav ul li a img {
background: url("../images/bulb.png") no-repeat;
border-width:0px;
height:16px;
line-height:22px;
margin-right:5px;
vertical-align:middle;
width:16px;
}
#nav ul li:nth-child(odd) a img {
background:url("../images/bulb2.png") no-repeat;
}
#nav a.sub:focus {
background:#bcbdc1;
outline:0;
}
#nav a:focus ~ ul li {
margin-top:0;

-moz-transition: 0.4s linear;
-ms-transition: 0.4s linear;
-o-transition: 0.4s linears;
-webkit-transition: 0.4s linears;
transition: 0.4s linear;
}
#nav a:focus + img, #nav a:active + img {
display:block;
}
#nav a.sub:active {
background:#bcbdc1;
outline:0;
}
#nav a:active ~ ul li {
margin-top:0;
}
#nav ul:hover li {
margin-top:0;
}

Answer

That's because if JavaScript is unable to work with with html loaded before the script. Put the whole script tag near the end of <body> after all content ,instead putting it in <head>, and it should work.

    </div>
    <!-- END MENU -->
<script src="myscripts.js"></script> 
</body>
</html>

If you want leave your js in <head>, you can wrap it all with window.onload like this

  window.onload = function() {
    //here goes the code
  };

but putting your js at the end of html file is considered a common good practice.

The whole html and js for reference:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" lang="es-es">
<link rel="stylesheet" href="style.css" type="text/css" media="screen">

</head>
<body>
    <!--Añadimos al area principal el efecto acordeon con el texto -->
    <div id="mainArea"> 
            <button class="accordion">Section 1</button>
            <div id="placeholder" class="panelacc"></div>

            <button class="accordion">Section 2</button>
            <div class="panelacc">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
            </div>

            <button class="accordion">Section 3</button>
            <div id="foo" class="panelacc">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
            </div>
    </div>

    <!-- MENU -->
    <div class="container">
            <ul id="nav">
                <li><a href="#"><img src="" /> Dashboard</a></li>
                <li><a href="#" class="sub" tabindex="1"><img src="" />Reporting</a><img src="images/up.gif" alt="" />
                    <ul>
                        <li><a href="llog.html"><img src="" />LYNIS LOG</a></li>
                        <li><a href="#"><img src="" />LYNIS REPORT</a></li>
                    </ul>
                </li>
                <li><a href="#" class="sub" tabindex="1"><img src="" />Lynis Tests</a><img src="" alt="" />
                    <ul>
                        <li><a href="#"><img src="" />Accounting</a></li>
                        <li><a href="#"><img src="" />Authentication</a></li>
                        <li><a href="#"><img src="" />Banner</a></li>
                        <li><a href="#"><img src="" />Boot</a></li>
                        <li><a href="#"><img src="" />Crypto</a></li>
                        <li><a href="#"><img src="" />File Integrity</a></li>
                        <li><a href="#"><img src="" />Firewall</a></li>
                        <li><a href="#"><img src="" />Hardening</a></li>
                        <li><a href="#"><img src="" />Kernel</a></li>
                        <li><a href="#"><img src="" />Logging</a></li>
                        <li><a href="#"><img src="" />Mail</a></li>
                        <li><a href="#"><img src="" />Malware</a></li>
                        <li><a href="#"><img src="" />Nameservers</a></li>
                        <li><a href="#"><img src="" />Networking</a></li>
                        <li><a href="#"><img src="" />PHP</a></li>  
                        <li><a href="#"><img src="" />Printing</a></li>
                        <li><a href="#"><img src="" />Processes</a></li>
                        <li><a href="#"><img src="" />Shell</a></li>
                        <li><a href="#"><img src="" />Software</a></li>
                        <li><a href="#"><img src="" />Squid</a></li>
                        <li><a href="#"><img src="" />SSH</a></li>
                        <li><a href="#"><img src="" />Storage</a></li>
                        <li><a href="#"><img src="" />Time</a></li>
                        <li><a href="#"><img src="" />Tooling</a></li>
                        <li><a href="#"><img src="" />Web</a></li>
                    </ul>
                </li>
                <li><a href="#"><img src="images/t2.png" />Overview</a></li>
            </ul>
    </div>
    <!-- END MENU -->
<script src="script.js"></script> 
</body>
</html>

JS code:

var textRecovered = localStorage.getItem("storedText");

if (textRecovered !== null){
    var lines = textRecovered.split("\n");
    window.localStorage.clear();
    for (i = 0; i < lines.length; i++) {
        console.log(lines[i]);
    }
}


var acc = document.getElementsByClassName("accordion");
for (var j = 0; j < acc.length; j++) {
    acc[j].onclick = function(){
        this.classList.toggle("active");
        this.nextElementSibling.classList.toggle("show");
    }
}

// selects the div with an id of placeholder
var div = document.getElementById('placeholder');


var fruits = ['I want a link <a href="http://google.com">here</a>','I want a link here','I want a link here','I want a link here','I want a link here'],
    ul = document.createElement('ul'); // create an arbitrary ul element

// loop through the fruits array
for(var i in fruits) {
        // create an arbitrary li element
    var li = document.createElement('li'),
         content = document.createTextNode(fruits[i]); // create a textnode to the document
         var link = "http://google.com";
         var element = document.createElement("span");
         element.innerHTML = fruits[i];
  li.appendChild(element); // append the created textnode above to the li element
  ul.appendChild(li); // append the created li element above to the ul element
}
div.appendChild(ul); // finally the ul element to the div with an id of placeholder
Comments