skip to Main Content

I am making a simple site, and I have three following files:

1st file:

# home.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test website</title>
</head>
<body>
    <h1>Welcome to my page</h1>
    <br />
    <button id="about">About me</button>
    <button id="contact">Contact me</button>
    <button id="pricing">Pricing</button>
    
    <script src="index.js"></script>
</body>
</html>

2nd file:

# about_me.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>About me</title>
</head>
<body>
    <h1>About me page</h1>
    <br />
    <button id="home">Home</button>
    
    <script src="index.js"></script>
</body>
</html>

3rd file:

# index.js
document.querySelector("#about").addEventListener("click", function() {
        window.location.href="about_me.html"
    })
    
    document.querySelector("#contact").addEventListener("click", function() {
        window.location.href="contact_me.html"
    })
    
    
    document.querySelector("#home").addEventListener("click", function() {
        window.location.href="home.html"
    })

The problem I am having is the following:

When I am at the home.html and click About me button, it takes me to the about_me.html file, but when I am in that page and click Home button it does nothing.

I have tried adding the JS code inside about_me.html file and it works that way.

Why it doesn’t work this way?

P.S. All of the files are in the same folder. And it works if I separate them in different JS files.

4

Answers


  1. Chosen as BEST ANSWER

    This worked in the end:

    document.addEventListener("click", function(event) {
        // Check which element was clicked using event.target
        if (event.target.matches("#about")) {
            window.location.href = "about_me.html";
        } else if (event.target.matches("#contact")) {
            window.location.href = "contact_me.html";
        } else if (event.target.matches("#home")) {
            window.location.href = "home.html"
        }
    });
    

  2. Try using:

    window.location = destinationPage;
    

    Or:

    window.location.assign(destinationPage);
    

    Instead of:

    window.location.href = destinationPage;
    

    Also, it would be good assign your events like this:

    document.addEventListener
    (
       'readystatechange', Event =>
       {
          if ( document.readyState == 'interactive' ) // or 'complete'
          {
             // The DOM is ready for management.
             // Assign your events here.
          }
       }
    );
    

    FULL SOLUTION:

    // #index.js
    
    const sitePages =
    {
      'home': 'home.html',
      'about': 'about_me.html',
      'contact': 'contact_me.html',
      'pricing': 'service_pricing.html',
    }
    
    document.addEventListener
    (
      'readystatechange', readyEvent =>
      {
        if ( readyEvent.target.readyState == 'interactive' )
        {
          for ( const buttonIdentifier in sitePages )
          {
            document.querySelector(`#${buttonIdentifier}`)?.addEventListener
            (
              'click', buttonEvent =>
              {
                const siteURL = sitePages[buttonIdentifier];
                const newURL = new URL(siteURL, new URL('.', document.location.href)).href;
                
                console.log('Should go to: ' + newURL);
                
                // Uncomment the next line to actually redirect.
                // document.location = newURL;
              }
            )
          }
        }
      }
    );
    <!-- file: home.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Test website</title>
        <script src="index.js"></script>
    </head>
    <body>
        <h1>Welcome to my page</h1>
        <br />
        <button id="about">About me</button>
        <button id="contact">Contact me</button>
        <button id="pricing">Pricing</button>
    </body>
    </html>
    
    <!-- file: about_me.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>About me</title>
        <script src="index.js"></script>
    </head>
    <body>
        <h1>About me page</h1>
        <br />
        <button id="home">Home</button>
    </body>
    </html>
    Login or Signup to reply.
  3. There’s no real problem in the HTML documents, but instead the script file.

    The problem is that JavaScript files load from top to bottom of the file. On the about page, it can’t find a button going to the about button, so it provides an error in the console and stops loading the rest.

    You can fix this by moving the order, which I don’t recommend that, because it will still result in an error although it will work.

    What I would do is make separate JavaScript files, I would like "a" tags (hyperlinks), or I would check to see if there was a button before adding an event listener to it, like this:

    if (document.querySelector("#about")) {
      document.querySelector("#about").addEventListener("click", function () {
        window.location.href = "about_me.html";
      });
    }
    
    if (document.querySelector("#about")) {
      document.querySelector("#contact").addEventListener("click", function () {
        window.location.href = "contact_me.html";
      });
    }
    
    if (document.querySelector("#home")) {
      document.querySelector("#home").addEventListener("click", function () {
        window.location.href = "home.html";
      });
    }

    I’ve been trying to post this for like 20 minutes, but I just posted on another question so I had to wait 30 minutes.

    I just saw your response, and it works but the only problem is it runs for every button on the page, which is possible to make it lag if there’s a lot of interactivity.

    Login or Signup to reply.
  4. Well, I copied your code and found out that the index.js file works only from home.html file,

    because I tried to define variables for those buttons and log them into the console while I was in about.html page but it logs nothing,

    Therefore you’re in front of two options:

    1. either create another js file and link it to about.html ONLY! and put the home button click event in it, and this will work fine.

    2. Or else put the text inside the button element into a tag and put the href value to the wanted page destination, For example:
      Instead of:
      <button id="home">Home</button> Use: <a href="home.html">Home</a>

    Both of these methods will work but I recommend you the second one anyway.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search