Using Jquery to Switch Pages

Recently, I've been experimenting with using hashes to create animated transitions between pages. Interestingly, the first page that loads (the home page) fades in and out seamlessly. However, when I attempt to navigate to another page, specifically the test page as indicated by the hash value, nothing happens. What could be the reason behind this issue?

<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"></script>
    <title>Jack Cook</title>
    <style>
    #navbar ul {
        list-style-type: none;
        display: block;
        text-align: center;
    }

    #navbar ul li {
        display: inline-block;
    }

    #navbar img {
        width: 64px;
        height: 64px;
        padding: 0 10px 0 10px;
    }

    #navbar a img:hover {
        opacity: 0.4;
    }
    </style>

    <script type="text/javascript">
    $(document).ready(function () {
      pages = {
        "home": ["Home", "This is my homepage!", "<p>Homepage</p>"],
        "test": ["Test", "This is a testing page", "<p>Testing</p>"]
      };

      page = window.location.hash != "" ? window.location.hash.substr(3) : "home";
      update(page);

      $(document).on("click", "a", function() {
        if ($(this).attr("href").substr(0, 4) != "http") {
          event.preventDefault();
          window.location.hash = "!/" + $(this).attr("href");
        }
      });

      $(window).on("hashchange", function () {
        $("body").fadeOut(1000, function () {
          update(window.location.hash);
        });
      });
    });

    function update(page) {
      $("body").css("display", "none");
      $("#content").html(pages[page][2]);
      $("body").fadeIn(2000);
    }
    </script>
  </head>
  <body>
    <div id="navbar">
      <ul>
        <li><a href="test"><img src="http://cdn4.iconfinder.com/data/icons/devine_icons/128/PNG/Folder%20and%20Places/Home.png" /></a></li>
        <li><img src="http://cdn4.iconfinder.com/data/icons/devine_icons/128/PNG/Folder%20and%20Places/Home.png" /></li>
      </ul>
    </div>

    <div id="content"></div>
  </body>
</html>

Answer №1

When using window.location.hash, the value will appear as '#!/test'

To test this out, follow these instructions:

var newPage = window.location.hash.replace('#!/', '');

update(newPage);

Answer №2

It appears that there is a need for you to modify the page parameter in the update function to remove any additional characters. When using square bracket notation, the property being referenced must match exactly with the string defining it. In its current state, you are attempting to access a property named ["#!/"], which does not exist.

function update(page) {
    $("body").css("display", "none");
    $("#content").html(pages[page.replace("#!/", "")][1]);
    $("body").fadeIn(2000);
}

See jsFiddle example here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to disable responsiveness on a website?

Currently, I am in the process of developing a responsive style sheet that is live on our website. However, it seems to display poorly on non-desktop devices due to being a work in progress. I am considering using JavaScript to enforce the desktop layout ...

What is the process of extracting a utility function from a helper file on a node.js server?

I'm facing a challenge with my node/express server where I need to access a function from a helper file in my app.js. The function in the helper file looks like this: CC.CURRENT.unpack = function(value) { var valuesArray = value.split("~"); ...

Should I return X in async functions, or should I return "Promise.Resolve(X)"?

I've always found this to be a tricky concept to fully grasp. Let's delve into async functions in Typescript. Which implementation is accurate? async function asyncFunctionOne(string1: string, string2: string, string3: string) { var returnOb ...

Enhance the appearance of TreeGrid nodes by customizing the icons according to the data within

Currently, I am working with the MUI DataGridPro component and my goal is to customize the icons of the TreeGrid nodes based on the data. This image illustrates what I hope to achieve: https://i.stack.imgur.com/nMxy9.png Despite consulting the official do ...

Refreshing Templates in Angular with ui.router

Initially, I apologize for the lengthy question, but it is necessary. Regrettably... I have multiple templates and routing logic stored in separate files. Strangely, the template I wish to load (depending on the selected region) does not initially load it ...

What is the best way to create multiple PDF pages using mpdf1?

Currently using mpdf1 and looking to generate a PDF with a table of 4000 rows. Any suggestions on how to achieve this using mpdf1? Is there a method to speed up the process and avoid waiting for several minutes? ...

Addressing the complications with the marginTop animation during scrolling

I need assistance with this particular code and .cscc .messages{ width:95%; height:200px; overflow:auto; } .message{ width:98%; &:hover{ background: #d6d6f0; cursor: pointer; } } .message-author{ float:left; } .message-date{ ...

Maintain the fixed position of the table header while scrolling

I am facing an issue with my table setup - I want the header to stay fixed while scrolling through the body. Here is how my table structure looks: <table> <thead> <tr> <th>Header 1</th> ...

Is there a way to adjust the saturation and desaturation of an image using CSS?

Issue Update After further testing, I have discovered that the desaturation effect is only functioning properly in Chrome. How can I adjust it to work in other browsers such as FF and IE? (Title modified) Currently, I am working on turning a color image ...

The browser prevented the script located at “http://127.0.0.1:5500/assets/platform.png” from loading due to an invalid MIME type of “image/png”

Sorry if this question seems repetitive, but despite extensive searching, I haven't been able to find a solution to my specific problem. I am currently working on developing a basic JavaScript game, but I'm facing challenges when it comes to impo ...

The position of the parent element's bounding box in relation to the child element

I've been mulling over this question for quite some time now, and I finally decided to bring it up. Hopefully, it's straightforward and not something that has been addressed before... Here's the scenario: I have a list of items with anchor ...

Is your URL getting cut off in jQuery?

How can I properly display a URL in an HTML table without it getting truncated? I'm attempting to show it within a table using jQuery, but it seems to be cutting off the URL. Here's a snippet of my code. Any suggestions on how to fix this? <! ...

Using the npm package in JavaScript results in a return value of 1

Recently, I have been working on turning this into an npm package: Test.tsx: import React from "react"; export default class Test extends React.Component { public render() { return ( <h1> Hallo & ...

Adding to the beginning of a list in JQuery mobile

Having trouble figuring out how to prepend my list in jQuery mobile while keeping the divider on top of the most recent item added. I attempted to prepend the newly added item, but it ended up shifting the divider to the bottom instead. function loadScan ...

Tips for setting up Reaction Roles in discord.js?

Having some trouble implementing this functionality, especially with my reaction role. Wondering if I am using the correct functions/methods. Any help would be greatly appreciated. New to discord bot development and might have a simple question, but any a ...

Having trouble with my Angular subscription - not behaving as I anticipated

I am facing an issue on my shop page where I have a FilterBarComponent as a child component. On initialization, I want it to emit all the categories so that all products are rendered by default. However, on my HomePageComponent, there is a button that allo ...

Troubleshooting Async Function compatibility between Express and NestJs

Initially, I set up a small express server to handle report generation and file writing tasks. var ssrs = require('mssql-ssrs'); var fs = require('fs'); const express = require('express') const app = express() const port = 30 ...

Occasional issue with Bootstrap where jQuery is required for JavaScript

Recently I have started implementing requirejs in my project, but I have encountered a persistent issue that I am unable to resolve. The error message "Bootstrap's JavaScript requires jQuery" randomly appears when I load my application. Below are the ...

Chrome does not recognize the 'position: fixed' style attribute

Encountered an issue in Chrome where the position:fixed property does not behave as expected. While this code works fine in Firefox and Safari, it seems to have a glitch in Chrome (69.0.3497.100). When scrolling, the blue div moves and reveals the green ba ...

The AngularJS component materializes almost instantaneously

Using AngularJS, I have developed an application where a certain section of code is displayed after the page loads for a split second: <div class="col-sm-4" data-ng-repeat="user in users"> <div class="card"> ...