Home > other >  Local storage and window.location.href.replace
Local storage and window.location.href.replace

Time:09-29

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>

CodePudding user response:

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

Check this post;

Code inside DOMContentLoaded event not working

CodePudding user response:

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

  • Related