Proceed to the following page without utilizing identical labels as the home page

As I work on coding a JavaScript function for my webpage, I am faced with the challenge of navigating to different pages without duplicating code. The "index.html" page contains all the necessary tags like html, head, title, and body, but I want to avoid redundancy when creating additional pages such as About, Contact, and Gallery.

Each new page should only include:

Bla bla bla

some other tags with text, photos etc

Is it possible to write JavaScript code that changes the content within the tags without repeating the entire document's code on every page?

I prefer using Chrome as my default browser and sticking to HTML and JavaScript (no PHP).

Thank you.

Answer №1

Utilize this function to resolve your issue by simply passing the ID of the div where you want to display the contents of a page with an index layout. In my demonstration, I am loading the content into a container div.

/**
     * Load page into url
     *
     * @param url           The url to load
     * @param onleave       The function to call before leaving
     * @param onenter       The function to call after loading
     */
function loadPage(url, onleave, onenter) 

{
    alert(url);
    console.log("loadPage("+url+")");

    // If onleave function specified
    if (onleave) {
        onleave();
    }

    var xmlhttp = new XMLHttpRequest();

    // Callback function when XMLHttpRequest is ready
    xmlhttp.onreadystatechange=function(){
        if(xmlhttp.readyState === 4){
            if (xmlhttp.status === 200) {
                console.log("Received content"+xmlhttp.responseText);
                document.getElementById('container').innerHTML = xmlhttp.responseText;

                // If onenter function specified
                if (onenter) {
                    onenter();
                }
            }
            else {
                document.getElementById('container').innerHTML = "Error loading page " + url;
            }
        }
    };
    xmlhttp.open("GET", url , true);
    xmlhttp.send();
    return;
}

Answer №2

Here's a suggestion to improve your website:

<!DOCTYPE html>
<html>
<head>
<script type="application/javascript">
function menuClicked(menu) {
    if (menu === "About") {
        var aboutMenu = document.getElementById("menuButton_1");
        aboutMenu.innerHTML = "Include relevant information about the About section here";
    } else if (menu === "Contact") {
        // Add functionality for Contact section
    } else if (menu === "Gallery") {
        // Implement Gallery section
    }
}
</script>
</head>    
<body>
<div id="menuButton_1" onclick="menuClicked('About')">
</div>
<div id="menuButton_2" onclick="menuClicked('Contact')">
</div>
<div id="menuButton_3" onclick="menuClicked('Gallery')">
</div>
</body>
</html>

You can utilize an "onclick" function to trigger actions when users click on menu buttons. By determining which button was clicked, you can dynamically update specific content elements on the webpage using JavaScript.

To modify multiple elements simultaneously, create additional variables in your script and target each element's ID to adjust their innerHTML individually based on user interactions.

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

Modify the values within two arrays in JavaScript

As a novice, I am attempting to code a function that will change values within an array. Specifically, my goal is to convert ºC to ºK. However, the current code I have written is not functioning correctly and is throwing an error message stating "j is un ...

extracting a characteristic from one entity and transferring it to another entity

Hey there, I have a tricky problem to solve. I am trying to extract a value from an array that's inside an object. $scope.document=[] $scope.accounts=[{name:"123"},{name:"124"},{name:"125"}] My goal is to take the first array element and append it ...

Using Javascript to replace elements with input fields and text areas

I'm currently working on a unique project for my Wordpress blog, where I am developing a custom block editor using JavaScript on the frontend. The goal is to convert all elements from the post content into a series of inputs and textareas. To begin, ...

The data event request in express using nodeJS is experiencing difficulties

I am currently facing an issue with the data event while trying to upload files using Express. Despite adding console logging tests, the data event doesn't seem to be working properly. Below is the server-side code snippet: var express = require(&ap ...

Developing Wordpress plugins involving images - path not found

I'm currently developing a WordPress plugin and encountering some issues with images. My plugin is located in wp-content/plugins/my-plugin/ directory, and within that, there's a folder named images/test.png - how can I properly reference this ima ...

How can I capture a Django "GET" event within a template using jQuery?

I have integrated a pdf download button in my Django project that generates a report. I want to display a modal indicating that the report is being processed when the button is clicked. Once the pdf is downloaded, I want the modal to automatically hide. H ...

Ways to duplicate ui-sref

I need to create a directive that enables clicks on an outer element to duplicate the ui-sref of one of its inner elements. This means that clicking on the outer element should have the same effect as clicking on the .cloned element. <div clone-click=" ...

What is the process for restarting the timer within a timer controlled by the react-countdown component?

Looking for guidance on how to implement a reset() function in ReactJS and JavaScript to reset a timer when the "Reset Clock" button is clicked on my webpage. The goal is to have the timer return to its initial value. Open to suggestions on how to achieve ...

Set the CSS/HTML to make two child elements occupy 50% of the height of the parent container div

This task seems deceptively simple, yet I am struggling to find a straightforward solution. Language: (HTML) <div class="col-6-12 subcontent-outer"> <div class="subcontent"> <h1>Header</h1> ...

Maintain the appearance of the text without the use of HTML tags

There is a specific div element on my webpage: <div class="container"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. <br><br> Ut enim ad minim veniam, ...

The execution of JSON.parse is rendered inactive

Currently, I'm facing a challenge trying to retrieve a JSON object from PHP to Javascript. Below is the Javascript code I've implemented: function GetEvents() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadyst ...

Issue with Selenium's send_keys() function sending an incomplete string

Issue at hand: Despite having a method in place to populate a field, the challenge lies in selenium not sending the complete string to the field, leading to failure of my assertion during verification. The code snippet: const webdriver = require('se ...

Is it possible for an AngularJS directive to compile a fresh element that has a second directive assigned to it?

UPDATE: All directives listed below will now require ng-model bindings to be applied in the elements they generate, targeting the controller assigned to the page. The code has been modified to reflect this. I am exploring the creation of dynamic HTML usin ...

Implementing React hooks to efficiently remove multiple items from an array and update the state

Looking for help on deleting multiple items from an array and updating the state. I have selected multiple items using checkboxes, which are [5, 4, 3]. My goal is to remove all these items from the array based on their ids and then update the state accordi ...

Unable to locate the image file path in React.js

I'm having trouble importing images into my project. Even though I have saved them locally, they cannot be found when I try to import them. import {portfolio} from './portfolio.png' This leads to the error message: "Cannot find module &apos ...

Enhance the appearance of div elements in GWT/HTML with custom styling

I am relatively new to GWT and have been exploring various options, but I have not yet found a solution to my issue. The challenge at hand involves developing a function schedule system in GWT, where I am working on designing the frontend. We currently ha ...

The powerful trio of Django, jQuery, and Ajax working together efficiently

I have a webpage with a text field at the top, a submit button and below that, a list of messages. I would like it so that when you click on submit after entering something in the textfield, the application saves the new message in the database and dis ...

Experiment with express router using mocha testing framework

Encountered an unusual routing behavior in Express (node.js). Attempting to test an API. The server mounts: app.use("/", productRouter); app.use("/", testRouter); productRouter.post("/products", ...); testRouter.post(" ...

How do I retrieve an index value from an array in GraphQL?

I am seeking a solution for obtaining the index of an array item that is not returned by downstream response. Let's consider my schema: schema: type Cart { items: [Item] } type Item { name: String index: Int } When the data comes in, it lo ...

Are there any jQuery plugins available for creating a currency input field specifically for the United States Dollar?

Looking for advice on creating an input field for a U.S. Dollar amount that includes AJAX feedback to format it with a "$" sign and maintain two decimal places, while disallowing letters and non-digits. Any suggestions for existing projects or tips on ho ...