I apologise if this is a duplicate, but I couldn't find anything that would help me. I want to make use of localStorage so that when you click a button on page 1, an element on page 2 gets a new class, all from within a single Javascript file. So far, when on page 2, the console tells me that the button from page 1 is null, so the code doesn't get executed properly.
I will be using localStorage to add classes extensively in my project, so hopefully the solution is nothing too complicated, and nothing that requires jQuery.
This is the HTML code for page 1:
<button type="button" id="button">Local storage</button>
<br>
<a href="page2.html">Next page</a>
<script src="main.js"></script>
And page 2:
<p id="output">Give me a class!</p>
<script src="main.js"></script>
And some simplified Javascript for both HTML files (main.js):
let button = document.getElementById('button');
let output = document.getElementById('output');
button.addEventListener('click', function() {
localStorage.setItem('someKey', 'someValue');
});
if (localStorage.getItem('someKey') === 'someValue') {
output.classList.add('some-class');
};
As I mentioned, the value of the button from page 1 is null when on page 2, which is why I think the if-statement at the bottom of the .js file doesn't get executed. This happens even when the variables are set locally instead of globally. Is it even possible to do everything from within a single Javascript file, or should I create two and import one into the other?