Henry Floyd
Henry Floyd

Reputation: 124

Javascript functions not being called

My website uses a nav bar which toggles divs on and off to go to different "pages". Recently the buttons have stopped responding (nothing happens when clicked, and nothing appears in the console), and I have not been able to figure out why.

My nav bar is formatted like so:

<a href="#" id="videosButton">videos</a><br>
<a href="#" id="graphicButton">graphic design</a><br>
<a href="#" id="webButton">web design</a><br>

My pages are formatted like so:

<div id="videos" class="page">Videos page</div>

The JS is:

$('#videosButton').click(function () {
document.body.style.backgroundColor="rgb(192,57,43)"
$(".page").hide();
$('#videos').show();
});

for each button. My JS file is being loaded, and I can view it in the console, so it's not an issue with that. I have been struggling with this for hours and I am at a loss. Can anybody help me understand why the nav bar is not behaving as expected?

EDIT: I have moved my external JS and jQuery to just before the closing </body> tag, and the problem persists. I have put up the complete website at http://hdf.bl.ee/test/index.html if anyone thinks there is an issue not in the code I posted.

Upvotes: 1

Views: 105

Answers (2)

Henry Floyd
Henry Floyd

Reputation: 124

It turns out the issue was something else entirely. Even though I moved my site's external JS file and the link to jQuery down to the </body> tag, they were being ignored because I had left one <script> in the <head> (the link to the Google API). When I moved that down with the other scripts, everything sudden began working. I am not sure why that was causing the other scripts to be ignored, but it solved my problem.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074238

Odds are that you're running that code before the element exists, and so $("videosButton") matches no elements, and so hooks up no handlers. Make sure the code is in a script tag after the markup for the elements in the HTML, or as a second-best approach, use jQuery's ready callback. Provided you do that, the function will get called:

$('#videosButton').click(function () {
document.body.style.backgroundColor="rgb(192,57,43)"
$(".page").hide();
$('#videos').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" id="videosButton">videos</a><br>
<a href="#" id="graphicButton">graphic design</a><br>
<a href="#" id="webButton">web design</a><br>
My pages are formatted like so:

<div id="videos" class="page">Videos page</div>

Upvotes: 5

Related Questions