Session storage is experiencing a logic problem where the class is not remembered upon refreshing, and jQuery is

As someone relatively new to jquery, I recently asked a similar question but am encountering difficulties with the final logic in this script.

The issue is that I have a script that adds a class of .prod__viewed whenever a div scrolls into the viewport. I also have a counter that displays the number of viewed items versus the total number of divs. My goal is to remember all the divs with the class .prod__viewed upon page reload using sessionStorage. However, currently, the script is adding the class to every div and I can't seem to figure out why.

$.fn.prodInViewport = function() {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();
    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();
    return elementBottom > viewportTop && elementTop < viewportBottom;
};


$(window).on('resize load scroll', function() {
    $('.prod__item').each(function() {
    if ($(this).prodInViewport()) {
        $(this).addClass('prod__viewed');
        sessionStorage.setItem('viewed', 'prod__viewed');
    } 
    });

  var numItems = $('.prod__item').length;
  var totalNumItems = $('.prod__viewed').length;
  var prodCountCheck = $('.prod__count__container');
  var positionY = $(this).scrollTop();
  var pageHeight = $(this).height();
  var scrollHeight = $('body').height();
  var scrollPercent = (positionY / (scrollHeight - pageHeight)) * 100;
  var prodCountElement = $('.prod__count__container').outerHeight();

  if (prodCountCheck.length == 1) {
    $('.prod__count__content')
      .html('<span>You&#39;ve seen <strong>' + totalNumItems + '</strong> of <strong>' + numItems + '</strong> prods</span>');

    $('.prod__load__bar').css({
      'top': prodCountElement,
      'width': scrollPercent + "%"
    });
  }
});



if (sessionStorage.getItem("viewed")) {
    $(".prod__item").addClass(sessionStorage.getItem("viewed"));
}
<section class="prod__count__wrapper">
    <div class="prod__count__container">
        <div class="prod__count__content"></div><!-- /.prod__count__content -->
    </div><!-- /.prod__count__container -->

    <div class="prod__load__bar"></div><!-- /.prod__load__bar -->
</section><!-- /.prod__count__wrapper -->


<section class="prod__wrapper">
    <div class="prod__container">
        <div class="prod__item">
            <div class="prod__item--img">
                <img src="https://images-na.ssl-images-amazon.com/images/I/81Lz-p7eRDL._SL1500_.jpg">
            </div><!-- /.prod__item--img -->

            <div class="prod__item--deets">
                <div class="prod__name">
                    My Hero Academia Two Heroes Blu Ray
                </div><!-- /.prod__name -->

                <div class="prod__price">
                    £14.99
                </div><!-- /.prod__price -->
            </div><!-- /.prod__item--deets -->
        </div><!-- /.prod__item -->

        <div class="prod__item">
            <div class="prod__item--img&qu"t;>
                <img src="https://images-na.ssl-images-amazon.com/images/I/81Lz-p7eRDL._SL1500_.jpg">
            </div><!-- /.prod__item--img -->

            <div class="prod__item--deets">
                <div class="prod__name">
                    My Hero Academia Two Heroes Blu Ray
                </div><!-- /.prod__name -->

                <div class="prod__price">
                    £14.99
                </div><!-- /.prod__price -->
            </div><!-- /.prod__item--deets -->
        </div><!-- /.prod__item -->
    </div>
</section>

If you have any insights on where I might be going wrong, your assistance would be greatly appreciated! Thanks for your help!

CodePen: https://codepen.io/nickelse/pen/vYYoVZ

Answer №1

Your usage of the jQuery addClass function is incorrect. The correct syntax for jQuery addClass is as follows:

$('selector').addClass('classname');

You can find more information about this function here.
The reason why "prod__viewed" is being assigned to all classes is because your selector targets all elements with the class prod__item (.prod__item).

It seems like what you're trying to achieve is something like this:

if (sessionStorage.getItem("viewed")) {
    $(sessionStorage.getItem("viewed")).addClass("prod__viewed");
}

Assuming your page is static, you can still make it work even if it's not. You want to save products to session storage when they're viewed. Since you can't save the entire DOM element to session storage, you need something to identify the products. Assuming each product has a unique ID, let's use that. Here's how you can save viewed products to sessionStorage:

// Create an object in sessionStorage at the beginning
sessionStorage.setItem('viewed', JSON.stringify([]))

// Add an item by using the ID and saving it to sessionStorage
viewed = JSON.parse(sessionStorage.getItem('viewed'));
viewed.push(ID) // ID of Product That Has Been Viewed
sessionStorage.setItem('viewed', viewed)

Now, at the start of the page, you can retrieve and apply the 'prod__viewed' class to viewed products like this:

viewed = JSON.parse(sessionStorage.getItem('viewed'));
for (ID in viewed) {
    $('selectorThatFindsProductOnID').addClass('prod__viewed');
}

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

Can you modify the current HTML code of a Wix website?

I am currently developing a website using Wix and have encountered an issue with the page description. Despite editing it in Wix, the changes are not reflecting on the live site. Upon inspecting the source code in Chrome, I identified the problem lies wi ...

Choose doesn't modify

There seems to be an issue with updating the value when changing the select option. The content inside the box should change based on the selected option, but it is not working as expected. Thank you in advance. FIDDLE $(function() { var all = "01234 ...

Achieving hover effects on <a> tags in CSS without using the href attribute

I'm looking to create a picture that changes when hovered over, and I've already achieved this using CSS by adjusting the z-index. However, I don't want users to be able to click on the image. To prevent this, I have removed the href from th ...

Prevent redirection when submitting and show an error message instead

I implemented a login system where, upon entering the correct username and password, a token is stored in local storage. If there's an error with the credentials, an "Login Unsuccessful" message is displayed. Everything was functioning correctly until ...

Display content within DIV element without causing a page refresh

I'm experiencing a small issue with loading addresses in my divs. I have a link that triggers a dialog box and loads the linked address into it, but when I click on the link, the dialog box opens briefly and then everything disappears! Here's w ...

Transform your .obj files into .glb files effortlessly with npm and Laravel

I've hit a roadblock for 2 days now and can't seem to find a solution. Could someone lend me a hand with this? Query: What's the best way to convert a .obj file to .glb? I attempted using obj2gltf npm package but integrating it with Larav ...

Transfer data from one array to another within a React application

I am dealing with this state structure: this.state = { data: { tags: [] }, items: [], input: '' }; My goal is to populate the tags array with the same values as the items array when submitting the data. var newData = t ...

When you hover over it, the text moves above the background content

I am looking to enhance my table by having the text expand and hover over the content with a white background. I have achieved the expand effect, but I am struggling to get the overflow to work properly. You can view the code in action on JsFiddle: JsFiddl ...

dealing with a situation where the call to the getElementsByTagname method returns null

Here is a snippet of JavaScript code that I am working with: <script language="JavaScript" type="text/javascript"> var sendReq = getXmlHttpRequestObject(); var receiveReq = getXmlHttpRequestObject(); var lastMessage = 0; var mTimer; ...

What is the best way to initiate a re-render after updating state within useEffect()?

I'm currently strategizing the structure of my code using React hooks in the following manner: Implementing a state variable to indicate whether my app is loading results or not The loading state turns to true when useEffect() executes to retrieve da ...

Caution: React is unable to identify the `PaperComponent` prop on a DOM element

Trying to create a draggable modal using Material UI's 'Modal' component. I want users to be able to move the modal around by dragging it, so I decided to use 'Draggable' from react-draggable library. However, I encountered this er ...

The error message states that there is a problem with the function task.dueDate.toDate,

I am currently utilizing Firebase as my database along with Next.js. I have encountered an issue when trying to read data from Firebase, specifically related to the due date field, which is of timestamp datatype. Here is the code snippet where I attempt to ...

Struggling with missing spaces when converting XML with HTML elements to CSV

I encountered an issue while trying to convert an XML file with HTML tags to CSV. For example, when I attempt to parse the following: "<strong>Nokia</strong> connecting people" from the XML description field using < strong > tags, in t ...

Encountering spacing problems among elements in the Dropdown Menu

I'm currently experiencing an issue with the Drop-Down Navigation menu that I created using HTML and CSS. When I tried to add padding between the list of UL elements, I noticed that the padding was inconsistent across the elements. For example, the st ...

Automatically focus on input when scrolling reaches a specific element using jQuery

I have been utilizing a jQuery plugin called Waypoints to handle scroll actions. My goal is to focus on the first input element of a section that is currently visible on the screen and then shift the focus to the input of the next respective sections as t ...

Include the ordinal indicator when a data entry is present in node.js

Currently, I am appending a timestamp as a prefix to the filename if it already exists in order to make it unique. However, I would like to enhance this by implementing an ordinal suffix. This means that if a file with a certain filename, like "helloworld ...

Modifying the innerHTML of SimpleModal and passing a parameter to a function causes an error to occur

I am currently working on a project where I have a collection of photos displayed on the index page. Each photo should trigger a modal that displays a larger version when clicked. However, I encountered an issue while attempting to use jQuery to modify the ...

Button clicking to zoom in and out with three.js

I am looking to include two buttons for zooming in and zooming out. How can I achieve this? I attempted to use the following code, but it did not work for me. var controls = new THREE.OrbitControls(camera, renderer.domElement); function zoomModel(isZoo ...

Different Methods of Joining Tables in SQLike

Struggling with creating a two-level JOIN in SQLike, currently stuck at the one level JOIN. The source tables are JSONs: var placesJSON=[{"id":"173","name":"England","type":"SUBCTRY"},{"id":"580","name":"Great Britain","type":"CTRY"},{"id":"821","name":" ...

"Learn how to empty a server-side textbox effortlessly with the help of

When I use a client function to clear a textbox (server control runat="server"), the textbox appears empty after clearing it with jQuery. However, when I trace the code and check the textbox.Text control, I find that the value is still there and not null. ...