javascriptjsonfunctionlocal-storagelocation-href

Local storage and window.location.href.replace


I and my course mate are trying to write a code where when the order button is clicked it should save on local storage and redirect to an order page.

So far when we click on order it is not registered in the application/local storage section of the google developer tool and thus does not redirect to a new page.

We put an eventlistener to show a console.log for when we click, just to be sure the buttons are in order(this part is not important).

We also used an online javascript validator to eliminate typos and errors.

Also do we need any specific code on the order.html file to interface with local storage?

  <!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title>grc</title>
  <link rel="stylesheet" href="css/style.css" type="text/css">
</head>

<body>
  <header>
    <nav>
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="groceries.html">Groceries</a></li>
        <li><a href="contact.html">Contact</a></li>
      </ul>
    </nav>
  </header>
  <main>
    <aside><img class="imgclass1" src="images/rounded logo.png" alt="Grocer Nigeria"></aside>
    <article class="preinventory">
      <section class="columns-desktop">
        <div class="inventory">
          <img class="sales" src="images/tomato.jpg" alt="Tomato"/>
          <div class="columns">
            <div class="title">Tomato</div>
            <div class="Price">$100</div>
          </div>
          <p class="Desc"> Our Tomato2</p>
          <button data-order="Tomato2">Order</button>
        </div>

        <div class="inventory">
          <img class="sales" src="images/tomato.jpg" alt="Tomato"/>
          <div class="columns">
            <div class="title">Tomato</div>
            <div class="Price">$100</div>
          </div>
          <p class="desc"> Our Tomato</p>
          <button data-order="Tomato">Order</button>
        </div>
      </section>
    </article>
  </main>
  <footer>
    <nav>
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="groceries.html">Groceries</a></li>
        <li><a href="contact.html">Contact</a></li>
      </ul>
    </nav>
  </footer>
  <script type="text/javascript">

    window.addEventListener("DOMcontentLoaded", function(e){
    const orderButtons= document.querySelectorAll("button[data-order]");

      orderButtons.forEach(function(button){
        button.addEventListener("click",function(e){
          const button= e.currentTarget;
          const container= button.parentNode;

          const order={
            id:button.getAttribute("data-order"),
            title: container.querySelector(".title").innerText,
            price1: container.querySelector(".Price").innerText,
            desc:container.querySelector(".desc").innerText
          };

          localStorage.setItem('order', JSON.stringify(order));

          const url = window.location.href.replace("grc.html","order.html");
          window.location.href = url;
        });
      });




    });
    window.addEventListener("DOMcontentLoaded", function(e){
      console.log("The page is loaded.");
    });
    const orderButtons= document.querySelectorAll("button[data-order]");
    orderButtons.forEach(function(button){
      button.addEventListener("click", function(e){
        console.log("The button was clicked.");
      });
    });
  </script>

</body>

</html>

  **Below is what I see when I run the live server**

<!-- Code injected by live-server -->
<script type="text/javascript">
    // <![CDATA[  <-- For SVG support
    if ('WebSocket' in window) {
        (function() {
            function refreshCSS() {
                var sheets = [].slice.call(document.getElementsByTagName("link"));
                var head = document.getElementsByTagName("head")[0];
                for (var i = 0; i < sheets.length; ++i) {
                    var elem = sheets[i];
                    head.removeChild(elem);
                    var rel = elem.rel;
                    if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") {
                        var url = elem.href.replace(/(&|\?)_cacheOverride=\d+/, '');
                        elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf());
                    }
                    head.appendChild(elem);
                }
            }
            var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
            var address = protocol + window.location.host + window.location.pathname + '/ws';
            var socket = new WebSocket(address);
            socket.onmessage = function(msg) {
                if (msg.data == 'reload') window.location.reload();
                else if (msg.data == 'refreshcss') refreshCSS();
            };
            console.log('Live reload enabled.');
        })();
    }
    // ]]>
</script>
</body>

</html>

Solution

  • The issue here is that the event DOMContentLoaded does not fire. Here is how I have used the load event instead; for redirection, I have simply used URL search params (because I don't know what your other html file looks like) although you may use your other html document instead.

    The snippet is below

    However note: Stackoverflow will not allow the JavaScript to run, and will throw a securityError. To run this code you must save it on your computer or use a 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 button = e.currentTarget;
          const container = button.parentNode;
          const id = button.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>