PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] How to prevent looking for DOM elements after window.location.href (redirection)

 October 15, 2022     dom, javascript     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing