Storing data locally and replacing the current URL with window.location.href

My course mate and I are working on writing a code that saves an order to local storage and redirects to an order page when the order button is clicked.

However, we are facing issues where clicking on the order button doesn't register in the application/local storage section of the Google Developer Tool and therefore does not redirect to a new page.

We added an event listener to display a console.log message when the button is clicked, just for troubleshooting purposes (this part is not critical).

We also used an online JavaScript validator to remove any typos or errors from our code.

Do we require any specific code on the order.html file to interact with local storage?

Answer №1

The problem at hand is that the DOMContentLoaded event is not triggering. To address this issue, I have opted to use the load event instead. For redirection purposes, I implemented the use of URL search params (due to lack of information about your other html file), but you can adjust it according to your specific needs.

Below is the code snippet

Please note: JavaScript will not execute on Stackoverflow and will display a securityError. To test this code, save it locally or use a platform like jsFiddle

function continue_ordering() {
  alert("Now continue with order");
};

window.addEventListener("load", function(e) {
  const orderButtons = document.querySelectorAll("button[data-order]");
  orderButtons.forEach(function(button) {
    button.addEventListener("click", function(e) {
      const btn = e.currentTarget;
      const container = btn.parentNode;
      const id = btn.getAttribute("data-order");
      const order = {
        id,
        title: container.querySelector(".title").innerText,
        price1: container.querySelector(".price").innertext,
        desc: container.querySelector(".desc").innerText
      };
      localStorage.setItem("order-" + id, JSON.stringify(order));
      window.location.search = "?ordering=true&order-id=" + id;
    });
  });
});
window.addEventListener("load", function(e) {
  if (window.location.search.search("ordering=true") != -1) {
    console.log("User is ordering");
    const params = new URLSearchParams(location.search)
    const id = params.get("order-id");
    if (!id || id == null) throw "There is no order id, error. Remove the ?ordering=true from the url and try again.";

    const order_info = JSON.parse(localStorage.getItem("order-" + id));
    if (!order_info) throw "Order information is not present: try ordering again. Remove the ?ordering=true from the url.";
    console.log("Order info is:\n", order_info);
    document.getElementById("ordering").removeAttribute("hidden");
    return;
  };
  document.getElementById("make-order").removeAttribute("hidden");
});
const orderButtons = document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button) {
  button.addEventListener("click", function(e) {
    console.log("The button was clicked.");
  });
});
<div id="make-order" hidden>
  <button data-order="test">Order</button>
  <div class="title">This is the title</div>
  <div class="price">130 USD</div>
  <div class="desc">Lorem</div>
</div>
<div id="ordering" hidden>
  <h1>
    You are ordering.
    <br> Choose
    <a href="javascript:location.search='';">Stop ordering</a> Or <a href="javascript:continue_ordering();">Continue with order</a>
  </h1>
</div>

Answer №2

Once the code tries to hook into it, the DOMContentLoaded event has already been triggered.

For more information on this topic, take a look at:

Code inside DOMContentLoaded event not working

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

ES6 Promises have a curious ability to accurately retrieve values from custom JavaScript objects

I have developed a unique library that functions independently from the Promise API, yet achieves similar objectives. It utilizes window.requestAnimationFrame and fallbacks to setTimeout, having no similarities with Promises. Interestingly, it is compatibl ...

Next.js is constantly encountering an issue where it throws an error stating "params

I've managed to establish a successful connection between my custom server using Node.js and Express.js with Next.js. The issue I'm facing is when trying to fetch a specific car by its id upon clicking it among other cars, as I keep encountering ...

What steps should I follow to run my JavaScript application locally on Linux Mint?

Currently, I am diligently following a tutorial and ensuring that each step is completed accurately. My goal is to locally host my javascript app at localhost:3000. Unfortunately, I am facing difficulties as every attempt to run npm run dev results in an e ...

What is the best way to retrieve a collection of DOM elements in JSX?

I'm in need of rendering certain components only if a specific condition is met. To achieve this, I have written the following inside the render() method: return ( <div className={classes.root}> {registrationScreen && ( * ...

What is the best way to implement filter functionality for individual columns in an Angular material table using ngFor?

I am using ngFor to populate my column names and corresponding data in Angular. How can I implement a separate filter row for each column in an Angular Material table? This filter row should appear below the header row, which displays the different column ...

What is the best way to separate a comma-delimited string in JS without including JSON data?

I have a string that looks like this: ABC, CDE, [{"ab":"1","cv":"23"},{"ab":"1","cv":"2%3A1639251967619%2C%22v%22%3A1%7D"}] My goal is to split it into an array of length 3, w ...

How to arrange a collection of objects in JavaScript

I am facing a challenge with sorting the array based on the address._id field of each object. Despite attempting to use the lodash orderby function, I have not been able to achieve the desired outcome. [{ rider_ids: '5b7116ea3dead9870b828a1a& ...

Is there a syntax error in Javascript when using a string and variable with the GET method?

Is there a way to send a value using the get method? In JavaScript, we need to use the + symbol to concatenate strings. But my issue goes beyond this simple problem. If I attempt the following: Let's say; var sID = 16; var rID = 17; EDIT-2: I act ...

Information regarding gender vanishes upon refreshing the page

When the page is refreshed, the variable called jso disappears. Is there an alternative method for storing information that does not involve using a button? The goal is to have it work seamlessly when the page is reloaded without requiring any user action. ...

Utilizing a Frozen Tensorflow Model with NodeJS for High-Performance Computing

I am new to tensorflowjs and js in general, but I have a trained model that I need to run on it. I have converted the model to json format, but I am having trouble feeding data into it: const tf = require('@tensorflow/tfjs') const tfn = require( ...

req.body is not defined or contains no data

I am facing an issue with my controllers and routers. bookController.js is functioning perfectly, but when I try to use userControllers for registration and login logic, req.body always appears empty. I tried logging the form data using console.log, but it ...

Iterate through a JavaScript grid and display the items

I am attempting to iterate through a JavaScript table, aiming to display the elements located between two selections made by the user. Here is an example of the table structure: if the user selects IDs 2 and 5, the loop should display rows 3 and 4. I trie ...

Angular Dom does not update when invoking a function within a separate component

Greetings everyone! I am facing a situation where one component (let's name it recipe component) has a reference to another component (named grocery component). The method in my recipe component uses the reference to the grocery component to call a s ...

Utilizing GraphicsMagick with Node.js to Extract Page Frames from Multi-Page TIF Files

I am currently working with a JavaScript script that can successfully convert a single page TIF file to JPEG. However, I am facing difficulties in determining whether "GraphicsMagick For Node" (https://github.com/aheckmann/gm) has the capability to extra ...

What is the best way to keep an image centered in the nav-bar as it decreases in size?

As I work on building a website using a template (https://github.com/learning-zone/web-templates/tree/master/victory-school-free-html5-bootstrap-template), I encountered an issue with the navigation bar. The original design appears like this: Before shrin ...

An elaborate warning mechanism in Redux-observable that does not trigger an action at the conclusion of an epic

I'm currently working on implementing a sophisticated alert system using redux and redux-observable. The requirements are: An action should request an alert: REQUEST_ALERT An action should create an alert and add an ID: SET_ALERT (handled in the ep ...

Exploring Material UI: Customizing the styling of components within TablePagination

Is it possible to customize the styling of buttons within the actions panel of the TablePagination component? import { withStyles } from '@material-ui/core'; import MuiTablePagination from '@material-ui/core/TablePagination'; const st ...

Having trouble accessing the loadTokenizer function in Tensorflow JS

As a beginner with Tensorflow.js concepts, I recently attempted to tokenize a sentence using the Universal Sentence Encoder in Javascript. You can explore more about it on Github Reference $ npm install @tensorflow/tfjs @tensorflow-models/universal-sentenc ...

Is Javascript Profiling a feature available in Firebug Lite?

Exploring the world of JavaScript profiles, I decided to step away from the usual Chrome Developer tools. Can Firebug Lite for Google Chrome provide Javascript Profiling functionality? ...

Is it safe to utilize an AngularJS filter for parsing a URL?

When working on a web application, my client-side (angularjs based) receives JSON data from a web service. The JSON can contain a text field with some URLs, such as: blah blah ... http://www.example.com blah blah blah ... To render these links as HTML, I ...