0

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>
  • `price1: container.querySelector(".price").innertext` if you are using whatever is inside of this element to set the price, ANYONE can change it by inspecting it with the dev tools. – Krokodil Sep 28 '21 at 09:14
  • _"and thus does not redirect to a new page"_ - the redirect is not dependent on that something actually got stored in localstorage. So if no redirect happens, either the complete handler function did not run (unlikely, although you should put a console.log into _that_ function to make sure everything is going okay, and not add an _extra_ one that does nothing but logging to console) - or your code ran into an error, which stopped further script execution. What does the browser console have to say? What happens when you step through the code in the debugger? – CBroe Sep 28 '21 at 09:17
  • I have uploaded what I see in debugger, hopefully It adds more context to the situation – MOON CREED Sep 28 '21 at 12:49

2 Answers2

0

The DOMcontentLoaded event has already fired by the time that code hooks it.

Check this post;

Code inside DOMContentLoaded event not working

SaminatorM
  • 630
  • 5
  • 18
  • Thank you, This actually gave us the desired result. Although we have been given steps to adhere to perform the task and the DOMcontentloaded seems to be in it – MOON CREED Sep 28 '21 at 13:34
0

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>
Krokodil
  • 1,165
  • 5
  • 19