Issue
In the index.html page I have the following code
<body>
<h1>First page</h1>
<button id="submitBtn">Submit</button>
<script src="script.js"></script>
</body>
The JS is a simple script that redirects the page to another page - second.html
document.getElementById('submitBtn').addEventListener('click', function(e) {
e.preventDefault();
window.location.href = 'another_file.html';
})
Once the second page is loaded, the console gives - TypeError: Cannot read properties of null (reading 'addEventListener'). This is understandable as the next page doesn't have the submitBtn.
How can I avoid this error?
Thanks
Solution
You can check if it exists before attaching events to it.
var elem = document.getElementById('submitBtn');
elem && elem.addEventListener('click', function(e) {
e.preventDefault();
window.location.href = 'another_file.html';
})
As for your design decision the way I would structure it indeed use script.js for all the functions and the only difference is between the pages which own has a minimal <script> tag to initialize and insatiate its own stuff.
So for this instance, while both share the same script.js, only index.html page would include this snippet of code inside of it. and second.html should not bother at all with checking for that element.
Answered By - IT goldman Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.