I have written the code for a simple function inline, but when i created a separate js.file it doesn't want to work for some reason. I've tried everything it feels like, but maybe my tired eyes can't something!
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="menu.js"></script>
</head>
<body>
<div class="container">
<button name="one">Button 1</button>
<p>
Lorem ipsum dolor sit amet
</p>
</div>
<div class="container">
<button name="two">Button 2</button>
<p>
Lorem ipsum dolor sit amet
</p>
</div>
<div class="container">
<button name="three">Button 3</button>
<p>
Lorem ipsum dolor sit amet
</p>
</div>
The idea is to have three buttons that when you click on one of them only one of the divs will be shown, and the other two will be hidden.
Here is the JavaScript (that worked perfectly fine inline):
var first_container = document.querySelectorAll(' div:not(:first-child) p');
for (var i = 0; i < first_container.length; i++) {
first_container[i].style.visibility = 'hidden';
}
var buttons = document.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', clickHandler);
}
function clickHandler(e) {
e.preventDefault();
var text = document.querySelectorAll('p');
for (var i = 0; i < text.length; i++) {
if (text[i] === event.target.nextElementSibling) {
text[i].style.visibility = 'visible';
} else {
text[i].style.visibility = 'hidden';
}
}
}
` tag? It seems to rely on the DOM having been loaded.
– Roy Prins Feb 06 '15 at 08:29