[Solved] JS isn't linking to button?!

Hi all

I’m having issues linking a js button on Github. I don’t think it’s a issue with Github pages, as it works with a few other sites.

Essentially, the buttons are meant to save the state of the checklist. It works on this codepen:

However, it is not working on my github project:

I believe I have linked to the JS properly, and I am really confused.

Thanks in advance!

Here is the JS:

var i, checkboxes = document.querySelectorAll('input[type=checkbox]');

function save() {
    for (i = 0; i < checkboxes.length; i++) {
        localStorage.setItem(checkboxes[i].value, checkboxes[i].checked); 
    }
}

function load_() {
    for (i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = localStorage.getItem(checkboxes[i].value) === 'true' ? true:false;
    }
} 

I have linked it in the header like this:

<script src="js/save.js" type="text/javascript"></script>

And then in the HTML doc:

  <button type="button" onclick='save()'>Save</button>
  <button type="button" onclick='load_()'>Load</button>

Not sure why it is not working :confused:

I forked your repo and moved the <script> element before the </body> tag. I think it’s now working as intended.

https://kevcomedia.github.io/pokefinder/

https://github.com/kevcomedia/pokefinder/commit/77649bcf80938881381de2bd6bf604b52486cee8

If you want I can make a PR :slight_smile:

2 Likes

Thanks! I’ll give it a go.

After thinking this question for an hour I found the solution dude.

Add script tags always before tag. Because html will process your tags line by line.

‘while checking solution someone gave the answer :)’

1 Like

Awesome, it works! May I ask why it doesn’t work in the header?

Thanks so much!

It doesn’t work when you put it in the head because at that point, the browser has not yet loaded the checkboxes. Note that the first line of your code looks for checkboxes in the page, but they haven’t loaded yet.

1 Like

Okay, thanks! Didn’t think of that.

Thanks for the awesome help.

I bet there is a lot of confusion for new web developers as to where to put the script tags. I learned early on (a few months ago - I’m fairly new) that your script tags/links should be at the end of body. Your HTML should be parsed first. There are examples abound everywhere of script tags located in the head of HTML documents. Even some documentation shows script tags in the head. There needs to be better education about this in general.

1 Like