Maintaining Changes in Javascript and CSS

I have created a header that can slide in and out of view with a toggle function. However, I want the header to be in the down position by default, without requiring users to click the toggle every time a new page loads. I have limited knowledge of JavaScript but I have managed to achieve the desired functionality using the following code:

<div id="headtoggle" onclick="headertoggle()"></div>
<script>
        function headertoggle() {
            var top;
            var pagetop;
            if (document.getElementById("page-header").style.top === "-210px") {
                top = "-11px";
                pagetop = "275px";
            } else {
                top = "-210px";
                pagetop = "80px";
            }
            document.getElementById("page-header").style.top = top;
            document.getElementById("page-body").style.top = pagetop;
        }
</script>

I am now looking for a way to modify the code so that it can remember the last setting for each user. I am open to using jQuery as well. Any guidance for a beginner coder like myself would be greatly appreciated.

Thank you, Dylan


EDIT2: I made some changes to the code provided and encountered a new issue.

 <div id="headtoggle" onclick="headertoggle()" onload="topposition()"></div>
<script>
    function topposition() {
        var top;
        var pagetop;
        if (localStorage.getItem("headerDown") == "false") {
            top = "-11px";
            pagetop = "275px";
        } else {
            top = "-210px";
            pagetop = "80px";
        }
        document.getElementById("page-header").style.top = top;
        document.getElementById("page-body").style.top = pagetop;
    }
</script>
<script>
    function headertoggle() {
        var top;
        var pagetop;
        if (document.getElementById("page-header").style.top === "-210px") {
            localStorage.setItem("headerDown", false);
            top = "-11px";
            pagetop = "275px";
        } else {
            localStorage.setItem("headerDown", true);
            top = "-210px";
            pagetop = "80px";
        }
        document.getElementById("page-header").style.top = top;
        document.getElementById("page-body").style.top = pagetop;
    }
</script>

The toggle functionality is working correctly, but when I execute "function topposition()" in the Firefox console, I receive the following error:

SyntaxError: expected expression, got end of script data:,/* EXPRESSION EVALUATED USING THE FIREBUG COMMAND LINE: */%0A%09function%20topposition() Line 2

Answer №1

To create a cookie, simply use the following code:

document.cookie="headerDown=true";

After moving the header back up, update the cookie by changing the value to false.

Upon loading the page, you can retrieve the cookie data to determine the current status.

Cookies can be accessed by using document.cookie, which returns a string containing all available cookies in the format:

cookie1=value; cookie2=value; cookie3=value;

Locate your specific cookie in the string to determine whether the header is up or down.

Answer №3

Utilizing local storage enables the persistence of variables during page reloads. To implement this, insert localStorage.setItem(name, value) within your if statements as illustrated below. If your usage of the headerToggle function is solely for positioning elements, the if statement following the function should be adequate. To ensure proper execution, place the if statement after the divs' HTML, preferably at the bottom of the page.

The code snippet below showcases the headertoggle function, which adjusts the position of elements based on a specific condition. By storing the state in localStorage, the function remembers the header's position across page loads for a seamless user experience.

function headertoggle() {
  var top;
  var pagetop;
  if (document.getElementById("page-header").style.top === "-210px") {
    localStorage.setItem("headerDown", true);
    top = "-11px";
    pagetop = "275px";
  } else {
    localStorage.setItem("headerDown", false);
    top = "-210px";
    pagetop = "80px";
  }
  document.getElementById("page-header").style.top = top;
  document.getElementById("page-body").style.top = pagetop;
}

if (localStorage.getItem("headerDown") == "true") {
  headertoggle();
}
headertoggle();

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

Displaying information from a database in an HTML form using PHP

Seeking assistance with managing data and populating: I'm in the process of creating an Employee database with two pages: 1. Add Employee 2. Modify Employee The "Add Employee" page requires input fields for EMP Name, EMP ID, Manager name (from a dro ...

Trigger the C# Click event with JavaScript fire function

Hi there, I could use a bit of assistance. My goal is to allow users to log in by hitting the "Enter" key on their keyboard. While I've successfully detected when the "Enter" key is pressed in my JavaScript code, I'm struggling with how to call m ...

Utilizing media queries for responsive design in CSS

I've been working on aligning the page content for different browser sizes using CSS. However, I'm having an issue with the first @media statement - no matter what changes I make in there, it doesn't affect the layout. I've been using ...

Enhancing navigation with creative hover effects

I've noticed a trendy effect on several websites and I'm curious about how it's done For example: When you hover over one of the navbar links, it appears as a button rather than a differently colored text link. How can I achieve this? I am ...

The list-image is nowhere to be found

Seeking assistance with my LI style CSS. Visit this link for reference I'm having trouble getting an image to float on the right side of my sidebar links, and my content is overlapping with the sidebar... .sidebar-menu ul { font : 14px font-fam ...

"Retrieving the most recent data within an ng-repeat directive using AngularJS

I am facing an issue with ng-repeat in my application. It successfully fetches values from the database and displays them in input text fields. However, when I update these values and click the save button, the updated values are not being saved. Can someo ...

The most convenient method for automatically updating Google Charts embedded on a webpage

I am facing an issue with refreshing a Google Graph that displays data from a MySQL database. The graph is being drawn within a webpage along with other metrics: Data Output from grab_twitter_stats.php: [15, 32], [14, 55], [13, 45], [12, 52], [11, 57], [ ...

The dynamic route parameter does not currently have compatibility with languages that utilize Unicode characters apart from the English

NextJS 13 (beta) Official Documentation provides information on dynamic route parameters in this link. Clarification: app/shop/[slug]/page.js To retrieve the slug, use params.slug. Example: app/shop/this-is-shop/page.js In this case, params.slug will o ...

Encountering an "undefined" error when implementing the useReducer hook in React

I'm encountering an error when using the UseReducer hook in React. Even though I have destructured the state object, I still receive this error: const [{previousOperand,currentOperand,operation},dispatch] = useReducer(reducer,{}); return ( ...

Error: 'window not defined' or 'document not defined' encountered while importing a module in Next.js

I'm working on integrating a Wysiwyg editor into my web application. However, I encountered an error when trying to import the editor module. I tried using both react-draft-wysiwyg and react-quill. The former resulted in a "window not defined" error, ...

How to access data from a child component in a Vue 3 template

Within my project, there are three Vue components that utilize the Composite API with the setup option. My goal is to access data within a nested tree structure. The code below provides a simplified version of what I am trying to achieve. The application ...

What mechanism enables the scores on this sports ticker to refresh automatically without relying on ajax calls?

While browsing scores on , I found myself intrigued by the way they update their scores without using ajax calls or iframes. It's a mystery to me how this functionality is achieved. Can anyone shed some light on how it works? ...

Access information via ajax from a php script

I am currently working on an AJAX code that sends data to PHP and then receives data from PHP... function updateDatabase(syncData){ $.ajax({ type : 'POST', async: false, url : 'php/syncData.php', ...

What is the process of declaring internal class variables within class methods in JavaScript?

Here's a query related to React JS. Can I define internal class variables within a method and then use them in other methods? For instance: class Something extends React.Component { state = { value: 'doesnt matter' }; somethin ...

What methods are most effective for designing a static side panel featuring a personalized tree-style list?

I am currently working on a sidebar design which is not rendering correctly, displaying a lot of flicker when expanded. I opted for b-nav instead of a traditional sidebar due to the interference it caused with my horizontal navigation bar. Here are my code ...

CSS: Centralizing a Div Element with Fluid Width

I've created a popup that appears in the center of the screen using: transform: translate(-50%, -50%); and position: absolute. However, I'm facing an issue where the width of the popup remains fixed instead of adjusting dynamically based on the c ...

Is there a way to maintain the checked status of the checkboxes after a page refresh?

Is there a way to keep the checkboxes checked even after the page is refreshed in this code snippet? Any code sample or explanation on how to achieve this would be highly appreciated. The complete project code can be found here: https://github.com/Orelso/P ...

The functionality of window.location.href seems to be malfunctioning on mobile devices within an ionic application

Attempting to open a view with a function call from the UI side <ion-option-button class="button-light icon ion-chatbubble" ng-click="openView('username')"></ion-option-button> The controller code for this action is as follows: $sc ...

Embedding Google+ Sharing in an iframe

I'm currently working on a web application that needs to be compatible with PC, tablets, and mobile phones. I'm interested in integrating Google+ Sharing into the app. However, it appears that when using the url , there are issues with blocking ...

The initial value set for the innerHTML property of a div element

I have a requirement in my application where I need to confirm if the container div is empty before adding specific text elements to it. The innerHTML of this div is frequently created and removed within the app, so it's crucial to validate its emptin ...