Develop an interactive website using JavaScript with a unique URL

My latest project involves creating custom elements using JavaScript and adding them to my HTML page. When the user interacts with these elements, I want them to be redirected to a new page that is dynamically generated through JavaScript.

I have a clear vision of how to update the current page with new content by clearing it and adding fresh elements. However, I'm facing a challenge in changing the web address to redirect users to entirely new pages.

To tackle this issue, I came up with an idea of utilizing an Array of Objects. My goal is to streamline the process by writing a single block of code that generates separate pages for each object within the array.

For instance:

const myArray = [{object: "First Object",},{ "Second Object"},{ "Third Object"},{ "Fourth Object"},{ "Fifth Object"}];
const customElements = window.customElements;

class MyElement extends HTMLElement {
    constructor() {
        super();
        this.innerHTML = `<a href="page2.html">${myArray.object}</a>`;
    }}
customElements.define("header-element", MyElement);

In the provided example, the JavaScript code creates links corresponding to each object in myArray, displaying their names. However, the link always directs to page2.html, which needs manual creation.

Instead of manually creating each link, I desire the JavaScript program to dynamically generate individual pages for every object without hardcoding paths. Clearing the existing page via CSS and inserting new elements won't suffice, as it only updates the content instead of changing the entire page structure.

The ultimate aim is to programmatically generate unique pages for each object in myArray with distinct URLs.

I stumbled upon a similar question related to dynamic HTML page creation using PHP: dynamically create HTML page from Javascript

Answer №1

To dynamically create pages, you can utilize the history.pushState function. Take this code snippet for example:

history.pushState({page: "page2"}, "Page 2", "/page2");

By using this function, a page with the URL "/page2" will be generated dynamically. To further enhance the dynamic nature of each page, consider using innerHTML to generate HTML code and create an Array of Objects containing varying data for each page.

Create links to each object by appending them to the base URL. Here's a demonstration:

let fruits = [
  {
    "name": "apple",
    "color": "red"
  },
  {
    "name": "banana",
    "color": "yellow"
  }
];

let baseURL = "www.mywebsite.com/";

for (let fruit of fruits) {
  let name = fruit.name;
  let link = document.createElement("a");
  link.setAttribute("href", baseURL + name);
  link.textContent = name;
  document.body.appendChild(link);
}

Note that this method won't affect the address when viewing the webpage locally. However, hosting the webpage on a server will result in changes to the web address.

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

What is the most efficient way to dynamically alter the position of a div element within an HTML document using

In a scenario where a parent div contains multiple child divs, it is required that one particular child div named .div_object_last always stays at the end. Below is an example setup : HTML <div class="div_parent"> <div class="div_object"> ...

React State not refreshing

Currently tackling a challenging e-commerce project and facing an obstacle with the following component: import React, { useEffect, useState } from 'react'; const Cart = () => { let [carts, setCarts] = useState([]); let [price, se ...

The performance of the bubble sorting program is not up to par

I am currently working on creating a bubble sort program in C# to sort random integers stored in an array. I need to implement this for arrays of various lengths such as 100, 1,000, 10,000, and so on. While I have some code that compiles correctly, it is n ...

Extracting properties from an object in NodeJS: a step-by-step guide

I'm struggling to access a specific property within an object using a GET request in NodeJs (with express). Here is the object I am working with: const friends = [{ id: 1, name: "laura", country: "England", language ...

What is the best way to link and store invoice formset with the main form foreign key in Django?

I am new to Django and need help. I am trying to save my invoice in a database, but the issue I'm facing is that I can't retrieve the foreign key from the main form when I try to save the formset. View.py def createInvoice(request):` if requ ...

What is the best way to showcase just 5 photos while also incorporating a "load more" function with

Is there a way to display only 5 images from a list on the first load, and then show all images when the user clicks on "load more"? Here is the code I have: $('.photos-list').hide(); $('.photos-list').slice(1, 5).show(); $ ...

Unable to successfully send multiple values from input fields using forms in PHP

I am currently facing an issue with my HTML form that contains a field consisting of multiple selection boxes as shown below: <div class="form-group"> <select multiple name="Fee[]"> ...

Locate the index position of an element in one array based on a corresponding element in a

I am seeking a way to determine the index and group that an item belongs to within a parent json group. Is there a method for achieving this? I am willing to modify the json format if necessary. I made an attempt using JSON.stringify(), but it seems to be ...

Experiencing Difficulty accessing Methods with Jmeter-Webdriver

var pkg = JavaImporter(org.openqa.selenium) var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait) var wait = new support_ui.WebDriverWait(WDS.browser, 5000) **var support_page=JavaImporter(org.openqa.selenium.WebDriver.Timeouts)** **v ...

What is the procedure for matching paths containing /lang using the express middleware?

I need to target paths that contain /lang? in the URL, but I am unsure how to specifically target paths that begin with /lang? I have two routes: app.get('/lang?..... app.get('/bottle/lang?....... I want to target these routes using app.use(&a ...

Exploring the KEY attributes within a JSON dataset

In my React project, I am working on displaying specific key values from a JSON response. For example, the fieldData {DMR_5_why_who_test: "test", why: test}. My goal is to only show the bolded or key values in my output. However, my current code is not a ...

Deactivate the button upon click using alternative methods besides the disable attribute

I am trying to implement functionality with 3 buttons: 'click me', 'disable', and 'enable'. When the 'click me' button is clicked, it triggers an alert. However, when the 'disable' button is clicked, it sho ...

JavaScript: Attempting to implement Highcharts without causing the browser to freeze

Is there a way to optimize loading multiple graphs without freezing the browser for too long? I want each graph to appear on the screen as soon as it's created, rather than waiting for all of them to finish rendering. I've tried using a similar ...

JavaScript: Unusual behavior discovered in forEach iteration

Here's the code snippet I'm having trouble with: someArray.forEach(x => { // do something console.log(‘calling api for ‘ + x); callAnHttpApiAsync(...); sleep(10); }); The issue lies in the asynchronous nature of the HTTP API call within ...

Achieving the minimum width of a table column in Material-UI

Currently I am in the process of developing a React website with Material-UI. One query that has come up is whether it's feasible to adjust the column width of a table to perfectly fit the data, along with some extra padding on both ends? Outlined be ...

Manually initializing Angular bootstrap with async in the Angular script tag

I am encountering an issue when trying to asynchronously download the Angular script in my application and manually bootstrap the application upon loading. The error message states: Failed to instantiate module wt due to: Error: [$injector:modulerr] htt ...

Using JavaScript to transform JSON information into Excel format

I have tried various solutions to my problem, but none seem to fit my specific requirement. Let me walk you through what I have attempted. function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) { //If JSONData is not an object then JSON.parse will ...

Tips for calculating the quantity of even numbers within a list provided by a user

As a beginner in the world of Python and coding, I find myself at a loss. I am struggling to grasp a simple explanation for how to count the number of even numbers entered by a user into a list. Any suggestions or tips would be greatly appreciated. Thank ...

The data retrieved from the backend is being stored in an object, however, it is not directly accessible through

After receiving data from the backend and storing it in an object, I am facing an issue where trying to print it using object properties shows undefined values. Here is a snapshot of my output: view image here Snippet of my code: this.documentService.getD ...

conditionally trigger one observable in rxjs before the other

I am in need of assistance or guidance regarding a challenge I am facing with rxjs that I cannot seem to resolve. In essence, my goal is to trigger an observable and complete it before the original one is triggered. Scenario: I am currently working on a ...