Streaming live at 10am (PST)

Hiding Element Based on Local Storage

Hi There,

I’m using the template & guide by Ben Parker here - How to create an upvote system in Webflow | Webflow Blog (specifically the vote & hard part as seen here - Vote and Hide).

However I’m having problems specifically with the hiding of some elements:

When a user clicks on one of my vote buttons a script is initiated which logs the id of the button they clicked on, stores it in the local storage and then hides any div elements with an id that matches what’s in the local storage (i.e. so a user can just ‘vote’ for 1 item once).

Here’s the script:

<script>
function myVote(shortcode) {
  $(document).on('submit', 'form', function() {
  // Set product in local storage
  localStorage.removeItem('_hjid');
	localStorage.setItem(shortcode, "true");
   // Refresh page after 3000 milliseconds
   setTimeout(function() { location.reload(true); }, 3500);
  });
};
</script>

It seems like sometimes the element is hidden and other times i get the above error, not sure what is causing this though!

Site is here - Tailwise BarkMark 2021 - Celebrating Our Four Legged Friends
Read only link - Webflow - Tailwise

Any help would be appreciated.

Hey Matt,

This is happening because localStorage persists between pages. To reproduce this, clear your localStorage, then go to one page and vote on an item. After voting, try visiting another page with the voting system, and the error should pop up. Essentially, the id from the first page, is still being considered on the other page, even if the id doesn’t exist on the other page, hence the property is null.

Here is a quick fix:

Remove the following from all pages containing the voting system:

<script>
for(let i=0; i<localStorage.length; i++) {
  document.getElementById(localStorage.key(i)).style.display = "none";
}
</script>

Now add this:

<script>
for(let i=0; i<localStorage.length; i++) {
  let el = document.getElementById(localStorage.key(i));
  if (el) {
    el.style.display = "none";
  }
}
</script>

You are now checking if the id actually exists in the DOM, if it does then set the style, else do nothing.

Hope this helps :smiley:

1 Like

Thanks so much David!

This has fixed it :slight_smile: .

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.