The local storage feature is failing to switch views and there are no error messages being displayed in

Seeking help with an issue I'm facing. I am attempting to create functionality where clicking on "Newsletters," "News," or "Public Announcements" alters the layout to display the correct view and saves it in localstorage.

Currently, when clicking on any of the mentioned items, the layout does not change, and data is not stored in localstorage...

Your assistance is highly appreciated.

Javascript:

$(document).ready(function(){
    // Changing layout to 'newsletters'
    $('.news_nav-for_nckcn ul li:nth-of-type(1)').on('click', function () {
        changeToNewslettersView();
    });

    // Changing layout to 'news'
    $('.news_nav-for_nckcn ul li:nth-of-type(2)').on('click', function () {
        changeToNewsView();
    });

    $('.news_nav-for_nckcn ul li:nth-of-type(3)').on('click', function () {
        changeToPublicAnnouncementsView();
    });

    if (typeof(Storage) !== "undefined") {
        var view = localStorage.getItem("view");
        if (view && view == "newsletters") {
            changeToNewslettersView();
        } else if (view && view == "news") {
            changeToNewsView();
        } else if (view && view == "publicAnnouncements") {
            changeToPublicAnnouncementsView();
        } else {
            // view isn't set, or is set to something we don't recognize
        }
    } else {
        // user's browser doesn't support localStorage
    }        
});
// Changing layout 'news' & 'publicAnnouncements' to 'newsletters'
function changeToNewslettersView() {
    var news=document.getElementById('hideClass');
    news.style.display="none";

    var publicAnnouncements=document.getElementById('hideClass');
    publicAnnouncements.style.display="none";

    var newsletters=document.getElementById('showClass');
    newsletters.style.display="block";

    storagePut("newsletters");

    $('.news_nav-for_nckcn ul li:nth-of-type(1)').addClass('active');
    $('.news_nav-for_nckcn ul li:nth-of-type(2)').removeClass('active');
    $('.news_nav-for_nckcn ul li:nth-of-type(3)').removeClass('active');
}
// Changing layout 'newsletters' & 'publicAnnouncements' to 'news'
function changeToNewsView() {
    var newsletters=document.getElementById('hideClass');
    newsletters.style.display="none";

    var publicAnnouncements=document.getElementById('hideClass');
    publicAnnouncements.style.display="none";

    var news=document.getElementById('showClass');
    news.style.display="block";

    storagePut("news");

    $('.news_nav-for_nckcn ul li:nth-of-type(2)').addClass('active');
    $('.news_nav-for_nckcn ul li:nth-of-type(1)').removeClass('active');
    $('.news_nav-for_nckcn ul li:nth-of-type(3)').removeClass('active');
}
// Changing layout 'newsletters' & 'news' to 'publicAnnouncements'
function changeToPublicAnnouncementsView() {
    var newsletters=document.getElementById('hideClass');
    newsletters.style.display="none";

    var news=document.getElementById('hideClass');
    news.style.display="none";

    var publicAnnouncements=document.getElementById('showClass');
    publicAnnouncements.style.display="block";

    storagePut("publicAnnouncements");

    $('.news_nav-for_nckcn ul li:nth-of-type(3)').addClass('active');
    $('.news_nav-for_nckcn ul li:nth-of-type(1)').removeClass('active');
    $('.news_nav-for_nckcn ul li:nth-of-type(2)').removeClass('active');
}
function storagePut(view) {
    if (typeof(Storage) !== "undefined") {
        localStorage.setItem("view", view);
    } else {
        // user's browser doesn't support localStorage
    }        
}

DEMO

Answer №1

The issue stems from attempting to access the element with the id "hideClass"

Upon reviewing your demo, we observed:

    <div id="2017-newsletters hideClass" class="nckcn_news_container-wrapper_newsletters">

It is important to note that according to this source, each element can only have one unique id:

In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Thus, in XHTML 1.0, the id attribute must be singular. This ensures well-structured XML documents. For XHTML 1.0, the id attribute should be used for defining fragment identifiers for the elements mentioned above.

An effective method for manipulating html tabs involves adding classes to hidden elements (or alternatively, applying a class to the visible element if preferred). In this way, elements can be accessed by class rather than by id.

Answer №2

It turns out that the news and related variables were actually null, causing an error when trying to access news.style, which ultimately led to the script getting terminated. I managed to correct the issue in the demonstration. Now, it is not only switching tabs but also properly setting the localStorage.

Check out the JsFiddle Demo here

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

Tips on incorporating a URL from a text file into a string

Could anyone assist me in adding a URL text file containing just one sentence and saving it as a string? Your help would be greatly appreciated. Thank you. ...

React Quill editor fails to render properly in React project

In the process of developing an application in Ionic React, I am in need of a rich text editor that can save data on Firestore. Despite initializing the editor as shown below and adding it to the homepage component, it is not rendering correctly although i ...

What are the steps for utilizing a button instead of an input field that is not within a form?

I need assistance with setting up a navbar with a button that will submit a form in the body with the ID of album_form. Can anyone provide suggestions for what to include in the onclick attribute to achieve this functionality? <body> <header& ...

Tips for triggering window load event on a particular page

I need to trigger the windows.load event on a specific page. Currently, I have set it up like this: $(window).load(function(){ if(document.URL == "/car-driving.html") { overlay.show(); overlay.appendTo(document.body); $('.popup' ...

How to execute an Ajax Post request within the Django framework?

I tried setting up a basic ajax/jquery post within a django framework, but I'm struggling to figure out why the output isn't appearing on a template page. Can anyone help? When I check the content of the post in firebug's 'response&apo ...

Issue with parsing JSONP using jQuery's AJAX request

I am encountering an issue with a jQuery ajax request that I have set up. Here is the code: jQuery.ajax({ url: serverAddress+'php/product.php', type: 'GET', jsonpCallback: "callback7", dataType: 'jsonp', d ...

Error: Callstack Overflow encountered in TypeScript application

Here is the code snippet that triggers a Callstack Size Exceeded Error: declare var createjs:any; import {Animation} from '../animation'; import {Events} from 'ionic-angular'; import { Inject } from '@angular/core'; exp ...

The combination of "object HTMLDivElement" with outerHTML and replaceWith() yields no results

I can't seem to figure out why this code is failing. I'm attempting to replace a DIV entirely using replaceWith from jQuery. I've tried multiple variations, but nothing seems to work. When I try outerHTML instead of html, I get [object HTML ...

What is the most effective way to condense these if statements?

I've been working on a project that includes some if statements in the code. I was advised to make it more concise and efficient by doing it all in one line. While my current method is functional, I need to refactor it for approval. Can you assist me ...

Efficiently deleting multiple items with PHP checkboxes and the power of ajax or jquery

I am hoping to enhance the functionality of my database table by enabling the deletion of multiple items using checkboxes. Initially, I achieved this using PHP, but now I am exploring the idea of implementing it with JavaScript to avoid page refreshes. How ...

Don't pay attention to the parent form tag in Bootstrap

Here is the code snippet I am working with: <div class="row"> <form id="update"> <div class="col-md-6"> <h1>Title</h1> </div> </form> <form id="insert"> <div class="col-md-6"> &l ...

Encountering a problem with the JavaScript promise syntax

Using pdfjs to extract pages as images from a PDF file and then making an AJAX call to send and receive data from the server is proving to be challenging. The implementation for iterating through the pages in the PDF was sourced from: The issue lies in pr ...

Is there a way to position the button and text side by side in a straight line

I am looking to have the button and text aligned on the same line. <div class="offers"> <div class="container" style="line-height: 300px; text-align: center;"> <h1>Enjoy our offers with your family <button class="offers-bu ...

Javascript: recursive function fails to return existing value

I'm attempting to recursively loop through an array in search of a key that matches a specified regex pattern. Once the condition is met, the loop should halt and return the value of the key. The issue I am facing is that although the loop stops corr ...

Media Query Failing to Perform as Expected

I have been working on implementing jQuery that can respond in sync with my CSS media queries on my website. Currently, I am facing an issue where certain objects slide onto the webpage at specific scroll points. To ensure that these objects remain respon ...

Issue with text input field causing the Enter key to not create a new line

In the example above, the text is placed in the middle of the text area. Here is the CSS code : .form-control { height: 300px; display: block; width: 100%; padding: 0.375rem 0.75rem; font-size: 1rem; font-weight: 400; line-heig ...

What are some popular methods for directing links to specific targets?

Do people still use iframes frequently in web design today? I'm currently developing a website using div elements and I'd like all content to be displayed within these container divs. Is there a way to achieve this without having to code the hea ...

JavaScript Link Replacement Magic!

I am trying to use JavaScript to update directory links. For example, I need to switch to . This is the code I currently have: <!DOCTYPE html> <html> <body> <img src="http://mysite.com/cdn/backup/Pic.jpg" /> <iframe src="http ...

Get your subscription using the Stripe Parse API

I am currently not able to find a way to retrieve a Stripe subscription using the Parse.com module from Stripe. Any insights on how this can be achieved would be greatly appreciated. Thank you! ...

Text cannot be highlighted within DIV element

Check out this page and this page on my website. Text within the advert DIV tag cannot be selected, and some text in the Incinerator product page is unselectable in the topic-div above the iframe element containing a YouTube video. Here is the relevant HT ...