``To easily navigate through web pages, visit the website for the most

Hi there! I am new to the world of Javascript and have been practicing building my own website. I'm looking for advice on the best way to navigate between pages.

  • index.html
  • pages/home.html
  • pages/about.html
  • pages/contact.html

One option would be to simply link to each page individually, but this means duplicating the same code for each page (which doesn't seem very efficient). Additionally, having URLs like www.mysite.con/pages/about.html is not very elegant; I would prefer something like www.mysite.com/about (without the ".html").

I've also experimented with using the load() function from JQuery to load page content into a specified div on my index page:

<div id="pageContentHere"></div>

This method allows me to use a single template for all pages, while keeping the URL consistent at www.mysite.com. However, I'm still open to suggestions on a smarter approach. How would you handle this navigation issue?

Answer №1

Great job on recognizing the flaws in your current setup. A more recent solution to consider is Single Page Applications, which, while potentially more resource-intensive, can be beneficial. Tools like React and GatsbyJS are examples of SPA frameworks that could work well for your static site, offering features like client-side routing and reusable components.

If you're looking for alternative options, exploring JavaScript templating engines might also be worth considering (check out this response).

Answer №2

I appreciate the valuable answers provided by everyone. In the end, I have decided to implement a solution that I believe strikes a good balance:

I have consolidated all pages into one and used Javascript to selectively display only the page I need:

(I can dynamically populate the content of the page divs using either jQuery or AngularJS without needing them to be physically present in the same file).

HTML

<div id="allPages">
    <div id="MainPage" class="page" style="background:red">
    Home page
    <ul>
        <li><a href="#SecondPage">Go to second page</a>
        <li><a href="#ThirdPage">Go to third page</a>
        <li><a href="#ForthPage">Go to forth page</a>
    </ul>
    
    </div>
    
    <div id="SecondPage" class="page" style="background:yellow">
    This is second page
    <ul>
        <li><a href="#MainPage">Go to home page</a>
        <li><a href="#ThirdPage">Go to third page</a>
        <li><a href="#ForthPage">Go to forth page</a>
    </ul>


    </div>
    
    <div id="ThirdPage" class="page" style="background:blue">
    This is third page
    <ul>
        <li><a href="#MainPage">Go to home page</a>
        <li><a href="#SecondPage">Go to second page</a>
        <li><a href="#ForthPage">Go to forth page</a>
    </ul>
    </div>
    
    <div id="ForthPage" class="page" style="background:green">
    This is forth page
    <ul>
        <li><a href="#MainPage">Go to home page</a>
        <li><a href="#SecondPage">Go to second page</a>
        <li><a href="#ThirdPage">Go to forth page</a>
    </ul>
    </div>
</div>

CSS

#allPages {
    position: absolute;
    width: 100%;
    /* display: flex; */
    height: 100%;
}

.page {
    border: 1px solid red;
    width: 100%;
    min-height: 100%;
    display: inline-block;
}

JS

$( document ).ready(function() {
    var url;
    url = getUrl();
    goToClickedPage(url)
    
    $("#allPages ul li a").click(function(){
        var linkTo;

        linkTo = $(this).attr("href");
        goToClickedPage(linkTo);
    });

});

function getUrl(){

    var url;
    url = ($(location.hash).length===0) ? "#MainPage":location.hash;
    console.log(url);
    return url;
}

function goToClickedPage(url){

    $("#allPages .page").hide();
    $(url).show();
}

While not the most elegant approach, I hope this solution proves helpful to others. Any additional tips are certainly welcome.

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

JQM activates upon the creation event

In order to refresh the DOM layout, I manually trigger the 'create' event using the following jQuery syntax: $(elem).trigger('create') Now, I am looking for a way to execute a callback function when the page has finished refreshing. I ...

Execute a Jquery Webservice function

Just starting out with Jquery and Ajax. I've been able to retrieve XML data from a web service, but now I need to convert it into an array for use with the AJAX GRIDVIEW. Below is my JS code, the result from the web method, and the desired array forma ...

Neither removing nor adding any classes

I'm working on implementing a star rating system and I've successfully made the stars turn yellow. However, I'm struggling with making them toggle back to white when clicked again. As a beginner in HTML, I'm not sure what's causing ...

Unveiling the ApplePay token with VueJS

I'm facing an issue with decrypting the ApplePay token in my Vue app, using a specific package. The error message I'm receiving is quite puzzling and I'm struggling to comprehend it. Simply checking if the package is installed by running th ...

Simulating service calls in Jest Tests for StencilJs

When testing my StencilJs application with Jest, I encountered an issue with mocking a service class method used in a component. The service class has only one function that prints text: The Component class: import {sayHello} from './helloworld-servi ...

The best way to centralize the input group in bootstrap

I attempted to center align my search bar, but it stubbornly stays to the left. Here's the code I'm using: <head> <style> html { overflow: auto; } html, body, iframe { ...

Exploring vuejs autocomplete functionality with Google Place API without utilizing callback functions

I'm currently working on implementing an autocomplete input box using the Google Places API. One thing I've come across is that the API URL needs a callback function to initialize the map. In my index.html file, I've referenced the Place AP ...

Pause the YouTube video when the modal is closed, following an AJAX load

I'm facing an issue with a small script that is supposed to stop YouTube videos from playing once their modals are closed. The problem arises when the HTML content is loaded through AJAX. Here is the script: $('#panelModal-1').on(&apos ...

Angular: Dynamically load Bootstrap modal with information from the selected item点击的元素加载数据

I am working with a list of items retrieved from a service, and I am using ng-repeat to display the data. What I want to achieve is the ability to open a bootstrap modal containing the specific data of the item that was clicked on. myApp.directive('o ...

Is it possible to update the content within an HTML paragraph without deleting the existing span elements

Check out this code snippet below from jquery UI, showcasing an alert box: <div class="ui-widget"> <div class="ui-state-error ui-corner-all" style="padding: 0 .7em;"> <p><span class="ui-icon ui-icon-alert" style="float: le ...

JavaScript conversion of arrays to JSON data structures

Here is the code snippet along with the variable 'polygon': var directionsDisplay; var directionsService = new google.maps.DirectionsService(); var map; var bermudaTriangle; var directionsPoints; var example; var rez; function initialize() { ...

Refresh the data in an existing Highstock chart with JavaScript only

I'm currently updating a website and unfortunately, I do not have access to the original code. All I am able to do is append new code at the end of it. The existing code consists of a highstock chart with specific data attributes. Here is the snippet ...

What is the top choice for creating a shallow copy of an array

While delving into the vue source code today, I stumbled upon a method of writing that left me puzzled. view source const deduped = [...new Set(pendingPostFlushCbs)] My initial thought is that it is a shallow copy of the array. But why is there a need t ...

What's causing the click event to only work on every second li element?

Let's tackle a simple to-do list scenario. Imagine inputting tasks and clicking submit, which then adds an item to the list. Clicking on an item should mark it with a line through the text. However, a peculiar issue arises: when multiple items are add ...

Sharing data between controllers in AngularJS is a key feature that enables seamless

There are two controllers: one controller will write data into an object and the other controller needs to read it. Is it possible to have a global variable in my app.js file that can be accessed by both controllers? I'm unsure why one would need to u ...

JQuery Dimmer and Non-Scrolling Functionality Cannot Be Used Simultaneously

My website has a Hamburger menu for the Mobile view that I toggle on and off using JQuery. The issue arises when I try to add a dimmer effect to the Main content while preventing scrolling to the Main content when the Hamburger menu is shown. When I attemp ...

Difficulty transferring function to child element

It seems like I may be overlooking something simple due to exhaustion, but I'm hoping someone can assist me! I have a function that the parent component inherits from the provider, and I am trying to pass it to the child as shown below: console.log(t ...

Finding the substring enclosed by two symbols using Javascript

I'm working with a string that contains specific symbols and I need to extract the text between them. Here is an example: http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_se ...

Expo running into issues with recognizing .jsx files when using Jest

I'm encountering an issue with running jest to execute its test suite on .jsx files within my Expo project. Here is my babel.config.js: module.exports = function (api) { api.cache(true); return { presets: ['babel-preset-expo'], }; ...

What is the way to create a "Table" that has horizontally wrapping rows in HTML5 and CSS3?

Presently, I am working with a table in HTML using tr and td tags. https://i.sstatic.net/MLDC0.jpg However, as the number of rows increase vertically, I face limitations due to lack of space. My goal is for the content to overflow horizontally like this: ...