Is it necessary to save the details of a specific position in local storage when sliding?

Currently, I am in the process of replicating a webpage design from . I have written the code for the functionality where images and phrases change on every slide. There are three different phrases and images that are being displayed, and my goal is to store the finalized user selection of image and phrase in the local storage. Below is a snippet of my HTML code:

window.addEventListener('load', function() {
      var rangeslider = document.getElementById("sliderRange");
      var output = document.getElementById("sliderOutput");
      var images = document.getElementById("sliderImages");
      rangeslider.addEventListener('input', function() {
        for (var i = 0; i < output.children.length; i++) {
          output.children[i].style.display = 'none';
          images.children[i].style.display = 'none';
        }
        i = Number(this.value) - 1;
        output.children[i].style.display = 'block';
        images.children[i].style.display = 'block';
      });
    });
    .rangeslider {
      width: 50%;
      margin: 0 auto;
      position: absolute;
    
    }
    .myslider {
      -webkit-appearance: none;
      background: white;
      width: 100%;
      height: 20px;
      opacity: 0.8;
      margin-top: 180px;
    }
    .myslider::-webkit-slider-thumb {
      -webkit-appearance: none;
      cursor: pointer;
      background: #000080;
      width: 33%;
      height: 20px;
    }
    .col-4 {
      text-align: center;
    }
    .myslider:hover {
      opacity: 1;
    }
    .image {
      position: relative;
      width: 400px;
      margin: 0 auto;
    }
    .image>img {
      position: absolute;
      display: none;
    }
    .image>img.visible,
    .image>img:first-child {
      display: block;
    }
    #sliderOutput>div {
      display: none;
    }
    #sliderOutput>div.visible,
    #sliderOutput>div:first-child {
      display: block;
    }
    #p1{
      height: 10px;
    }
  <div class="image mt-3 mb-3" id="sliderImages">
      <img src="../static/images/1.jpg" width="400" height="180">
      <img src="../static/images/2.jpg" width="400" height="180">
      <img src="../static/images/3.jpg" width="400" height="180">
    </div><br>
    <div class="rangeslider">
      <input type="range" min="1" max="3" value="1" class="myslider" id="sliderRange">
      <div id="sliderOutput">
        <div class="container">
          <div class="row mt-4">
            <div class="col-4">
              <h6 class="display-6">Starting From Scratch</h6>
              <p> I'm designing the room </p>
            </div>
            <div class="col-4">
              <h6 class="display-6">Somewhere in Between</h6>
              <p>I'm designing around a few pieces I already own</p>
            </div>
            <div class="col-4">
              <h6 class="display-6">Mostly Furnished</h6>
              <p>I want to put the finishing touches on my room</p>
            </div>
          </div>
        </div>
        <div class="container">
          <div class="row mt-4">
            <div class="col-4">
              <h6 class="display-6">Starting From Scratch</h6>
              <p> I'm designing the room </p>
            </div>
            <div class="col-4">
              <h6 class="display-6">Somewhere in Between</h6>
              <p>I'm designing around a few pieces I already own</p>
            </div>
            <div class="col-4">
              <h6 class="display-6">Mostly Furnished</h6>
              <p>I want to put the finishing touches on my room</p>
            </div>
          </div>
        </div>
        <div class="container">
          <div class="row mt-4">
            <div class="col-4">
              <h6 class="display-6">Starting From Scratch</h6>
              <p> I'm designing the room </p>
            </div>
            <div class="col-4">
              <h6 class="display-6">Somewhere in Between</h6>
              <p>I'm designing around a few pieces I already own</p>
            </div>
            <div class="col-4">
              <h6 class="display-6">Mostly Furnished</h6>
              <p>I want to put the finishing touches on my room</p>
            </div>
          </div>
        </div>
      </div>

My primary requirement is that when the slider is on the first position, both the selected phrase and image should be stored in the local storage. Similarly, as the user makes selections on other slides, those details should also be saved accordingly.

Answer №1

Do you need to recall the last slide the user viewed? If so, consider using the localStorage.setItem() method along with the dataset feature to mark each slide.

If my assumption is correct, your onload function would have this line to set the default to the first slide:

localStorage.setItem('currentSlide', '1')

Each of your HTML slides could have a dataset tag like this:

data-index="1"

In your change slide function, retrieve the dataset value and update the localStorage parameter:

function changeSlide() {

   // ... Your existing code...

   localStorage.setItem('currentSlide', this.dataset.index);
}

If you don't want the website to remember the user's position after leaving the page, consider using sessionStorage instead: https://developer.mozilla.org/en-US/docs/Web/API/Storage

Answer №2

To save your image, utilize the saveImage function

Here is the HTML:

<img src="../static/images/1.jpg" id="bannerImg" />

Here is the JavaScript:

function saveImage() {
    var bannerImage = document.getElementById('bannerImg');
    var canvas = document.createElement("canvas");
    canvas.width = bannerImage.width;
    canvas.height = bannerImage.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(bannerImage, 0, 0);

    var dataURL = canvas.toDataURL("image/png");

    localStorage.setItem("imgData", dataURL.replace(/^data:image\/(png|jpg);base64,/,"");
}

Once the processing is complete, you can retrieve your image from local storage

HTML:

<img src="" id="tableBanner" />

JavaScript:

function getImage() {
   var dataImage = localStorage.getItem('imgData');
   bannerImg = document.getElementById('tableBanner');
   bannerImg.src = "data:image/png;base64," + dataImage;

}

Be sure to execute both of these functions to solve your issue

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 effective method for incorporating parameterized aesthetics using CSS in a JSP program?

I am currently working on a JSP web application without the support of any framework, unfortunately. This application is intended to serve multiple customers, each with their unique set of colors and company logos. The overall layout of the CSS will remai ...

What is the process for extracting a numerical value from a text box and using it to update a database?

Trying to figure out how to add a numerical value entered into a text box to a value in a database table when the submit button is clicked. Let's say there's a table called customers in the database, with columns for name and balance. The goal i ...

"Maintaining Consistency: Ensuring The First Row is Repeated on Every

When trying to save a PDF using jspdf, I encountered an issue with tables in my HTML. The tables do not have headers, but JsPDF is automatically repeating the first row of the table on every page, causing overlap. I don't want headers on every new pag ...

What is the best way to deploy a nodejs expressjs application to a server?

I have successfully developed a nodejs and express application that works perfectly on my localhost. To start the application, I simply run the command npm start or node index.js. Recently, I uploaded all the necessary files, including node_modules, to a ...

Troubleshooting Issues with JavaScript Counter and JSON Integration

When manually inserting a number into the HTML, the counter works fine. However, when pulling data remotely, there seems to be a problem. The remote data is logging correctly in the console and appears properly in the DOM element when the counter code is d ...

Transform the array into an object containing corresponding key-value pairs

In my dataset, I have an array containing various values: [ { "factor": { "data": "f1", "val": [ "val1" ] } }, { "factor": { "data": "f2", "val": [ "val2" ] ...

Rearrange element's placement using Jquery Drag & Drop

I am experiencing difficulties in positioning my elements after a drop event. Within my "list" of divs... In order to keep the divs together and update the list, I utilize jQuery's append function to move the element from the list to its designated ...

Uh oh! An error occurred when trying to submit the form, indicating that "quotesCollection is not defined" in Mongodb Atlas

Displayed below is my server.js file code, along with the error message displayed in the browser post clicking the Submit button. const express = require('express'); const bodyParser = require('body-parser'); const MongoClient = require ...

issue with stacking data in Google Charts

Check out my HTML code: <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript" src="https://www.google.com/jsapi"></scri ...

Guide to comparing 2 arrays and determining the quantity of identical elements

If an AJAX call returns 2 arrays upon successful execution, the arrays will be different each time but may contain some common elements. For instance: array1 = [x, y, z, a] array2 = [x, y, y, y, x, z, y, z, z] The goal is to determine how many times eac ...

How to eliminate quotation marks from an array in JavaScript?

const original_data = ["alpha,beta,gamma","1,2,3","apple,banana,cake"]; updated_data = ["alpha,beta,gamma,1,2,3,apple,banana,cake"] The function is returning the original_data, but I require the updated_data. ...

Issue: React error message indicates that the .map() function is not recognized. The API response is in the form of an object, making

As a newcomer to REACT.JS, I am currently facing the challenge of extracting data from an API for my project. Utilizing "Axios" for sending the get request, I have encountered a situation where the response comes back as an array in one API and as an objec ...

Iterate through the classes for updates rather than focusing on individual id fields

I am currently working on creating a function that can refresh data with an AJAX call for multiple instances of a class within a single page. The function functions perfectly when there is only one instance on the page: $(document).ready(function() { ...

Organizing numerical values within for loops

I'm having trouble determining prime numbers and non-prime numbers. When I follow the logic of looping through numbers from 2 to 100, it makes sense for primes. However, when I start at 0 and loop by y + itself, it seems counterintuitive to me. For ex ...

Troubleshooting the issue: Unable to shift a div to the left in a Rails app using jQuery and CSS when a mouseover event occurs

Hey there, I'm working on a div that contains a map. My goal is to have the width of the div change from 80% to 50% when a user hovers over it. This will create space on the right side for an image to appear. I've been looking up examples of jqu ...

Shopping Directive Coverage Discrepancy

In my application, there is a shop item directive that includes a price attribute. When a user interacts with the directive, the total cost (a variable stored in the main controller) should be updated by the price of the item that was clicked. Unfortunate ...

Is it just me or does my wrapper always hover above the bottom of the screen?

I have been working on coding a simple layout that I created last year. Most of the work is done, but I ran into an issue where the 'wrapper' div doesn't extend to the bottom of the page as expected. It almost looks like it has the "position ...

Using Node and Express to handle form submissions, we can create a POST request that sends data to the server

Despite my ongoing learning journey, I am feeling a bit frustrated as I struggle to find a solution for this particular issue using ES6 Javascript. Currently, I have a straightforward todo-list web-app where everything is managed and displayed through the ...

What could be the reason for the component bindings being undefined within the controller?

I'm currently working on a basic angular component. I have set up a parameter as a binding and managed to display its value on the screen successfully. The parameter displays correctly, but when I try to access it within the controller, it shows undef ...

Struggle with uploading images in codeigniter

My issue lies in saving data to the database after displaying it on the front end. Specifically, I have a problem with the image upload function. When I try to save the image path in the database, it saves the full file path like C:/xampp/www/htdocs/rentoz ...