Reputation: 33
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?
Upvotes: 0
Views: 7357
Reputation: 2646
I'll attempt to answer this question without all the information.
Local storage works on a per domain basis (not per page) so any HTML pages will share the same LocalStorage
database as long as they are on the same domain.
If you are currently developing your web application by opening websites through the filesystem ie: file://C:/Users/UserA/Documents/WWW/index.html
the browser cannot detect that 2 different pages are on the same domain so it will create a new LocalStorage
database for each instance.
You can get around this by hosting your web application through a Local or Remote webserver that your accessing the website via http://localhost:8080/index.html
or https://example.com/index.html
Upvotes: 4