What are the signs that an element was visible on screen prior to navigation?

Recently, I incorporated SlideUp and SlideDown jquery animations into my website. You can check it out by visiting (click the >>>). However, I noticed a small issue where when users navigate to a new page, they have to re-SlideUp the element that was slid up on the previous page. Is there a way to detect if the element was visible before navigation?


$(function(){ 
    if (sessionStorage.getItem("tabvisible")) {
        $(".jumbotron").slideDown(); // displaying header
    } else {
        $("jumbotron").slideUp(); // hiding header
    }

    $('.information').hide().fadeIn('slow');

    $("#expandiconup").click(function(){
        $(".jumbotron").slideUp();
        sessionStorage.setItem("tabvisible", false);
    });
    
    $("#expandicondown").click(function(){
        $(".jumbotron").slideDown();
        sessionStorage.setItem("tabvisible", true);
    }); 
});

Answer №1

Have you considered utilizing localStorage for this task?

$("#expandiconup").click(function () {
    localStorage.setItem("tabvisible", false);
});

$("#expandicondown").click(function () {
    localStorage.setItem("tabvisible", true);
});

Upon loading the new page, check for the stored value

if (localStorage.getItem("tabvisible") == true) {
    //display header
} else {
    //hide header
}

Answer №2

Implementing this feature with JavaScript may not be the most straightforward task, and there are likely more efficient methods available than the one I'm about to suggest. Consider exploring front-end frameworks like Angular to manage your views, ensuring that your header remains static without needing to reload and maintaining state across pages.

To achieve this functionality through a workaround, you can utilize the CSS :target pseudo-selector along with some JavaScript. Essentially, upon clicking the "show" link, you would use JavaScript to add a hash to each navigation URL. When these links are clicked, the new page will load with a corresponding hash at the end. If this hash matches an element ID on the page (representing the content to show/hide), you can leverage the CSS :target pseudo-selector to hide it using display: none.

Here's a basic example (demonstrated in CodePen, but requires actual HTML pages to function properly):

HTML

<!-- HTML code omitted for brevity -->

CSS

#headerHidden:target {
  display: none;
}

JavaScript (using jQuery)

// JavaScript code snippet provided above

This approach may seem somewhat unconventional, but it presents an interesting solution to your problem. One potential drawback is the browser may scroll to the element corresponding to the hash in the URL. In this case, as the element is at the top of the page, this should not pose a significant issue.

While my markup differs from yours, I trust that you grasp the concept and extract any useful elements from this explanation!

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

When using jQuery to select elements of a specific class, make sure to exclude the element that triggered the

A dynamic number of divs are generated from a data source. Each div contains an image button and another div with text. While the actual scenario is more complex, we can present a simplified version: <div id="main"> <div id="content_block_1" ...

What is the best way to obtain the SearchIDs for various searchNames using JavaScript?

Who can assist me in resolving this issue? I am trying to retrieve the id of a searchName whenever a user selects the checkbox. Ideally, I would like to assign the value of the PHP line $search_row->searchid to the id attribute in the input field. Apolog ...

Discovering the unique identifier of an item in Node.js is simple with these steps

I have a delete API which requires the item's unique ID to be passed in for deletion. How can I capture the ID of the item being deleted and send it to the API? Here is the API: app.post("/delete_product", function (req, res) { var data = { ...

When mousing over a subitem of the Image menu, ensure that the Image menu

Is there a way to prevent the image menu from reverting back to its original image when hovering over its subitems? I have 5 navigation menu items, but only one has a dropdown. Whenever I hover on the subitems of About Us, the image for About Us changes ba ...

Is it possible to create a button function in HTML that can alter the CSS image tag?

Is there a way I could create a function that can retrieve a value, update an image source, and then incrementally select another value? It would be incredibly helpful if you could provide a reference where I could learn how to do this or explain it in det ...

What is the best way to assign a unique ID to every element in this situation?

Here is the given code: var words = ['ac', 'bd', 'bf', 'uy', 'ca']; document.getElementById("wordTable").innerHTML = arr2tbl(2); function arr2tbl(ncols) { return words.reduce((a, c, i) => { ...

Is it possible to locate and eliminate the apostrophe along with the preceding letter?

My objective is to tidy up a character string by removing elements that are not essential for the user and SEO, specifically the (letter before the apostrophes) in this case. I am looking for a regex solution or explanation of how to achieve this in PHP, a ...

Images Centerfold Team

I am facing a challenge in creating a group of images for an album. There seems to be a significant gap on the right side, which cannot be resolved without using padding. However, adding padding only works for my current PC resolution and creates a larger ...

Passing parameters in a callback function using $.getJSON in Javascript

I am currently using a $.getJSON call that is working perfectly fine, as demonstrated below. var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?"; $.getJSON(jsonUrl,function(zippy){ ...some code } However, I want to pass a ...

`Resolving CORS error when setting up an AWS Lambda function with API Gateway on AWS`

In the AWS lambda function provided below, I have set it up to call an API that lists all country names. The function is connected to an API Gateway and works as expected when tested with Postman. Here is the code snippet: import axios from 'axios&apo ...

The message "jest command not recognized" appears

My test file looks like this: (I am using create-react-app) import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Calculator'; import { getAction, getResult } from './actions/' ...

Is it possible for the ".filter" function to verify if the target contains multiple attributes?

I'm currently working on a checkbox filter setup and using Jquery's .filter to sort through some divs. Below is the snippet of Jquery code that I am using: $(document).ready(function(){ var checkboxes = $('div.filter-groups').find(&ap ...

What is the solution to having a div move along with window resizing without displacing adjacent divs?

After much effort, I still can't seem to get this working correctly. I've been playing around with a section named "RightExtra" and a div inside it called "RightExtraContent". My goal is to allow these two divs to move freely when the window is ...

RadAjaxNamespace is not found within the codebase

While testing the application on my development machine, I encountered an error message in the browser debug console stating "RadAjaxNamespace is not defined". Interestingly, this error does not appear when accessing the production server. Upon comparing t ...

Ajax call encounters 404 error but successfully executes upon manual page refresh (F5)

I am encountering a frustrating issue with my javascript portal-like application (built on JPolite) where modules are loaded using the $.ajax jquery call. However, the initial request fails with a 404 error when a user first opens their browser. The app i ...

The Ajax response is not providing the expected HTML object in jQuery

When converting HTML data from a partial view to $(data), it's not returning the jQuery object I expected: console.log($(data)) -> [#document] Instead, it returns this: console.log($(data)) -> [#text, <meta charset=​"utf-8">​, #text, < ...

A pair of buttons each displaying a unique div block

I am facing an issue with my jQuery script. I want to be able to click on one of the previewed text associated with a button and then have the other one close automatically. The desired effect is for the text to slide down using slideDown() and disappear ...

Reorganize items that extend beyond the list into the next column using Bootstrap

I have a row with two columns, where Column 1 currently contains 7 list items under the ul tag. However, I want to display only 5 list items in Column 1 and automatically move the remaining items to the next column (i.e., Column 2). Is there a way to ach ...

Using Javascript/JQuery to extract numbers from a URL with regex or alternative methods

I need help extracting a specific group of consecutive numbers from the following URLs: www.letters.com/letters/numbers/letters" and www.letters.com/letters/letters/numbers/symbols Is there a way to isolate only the continuous sequence of numbers in th ...

Regain focus after selecting a date with Bootstrap datepicker

When initializing a bootstrap datepicker from eternicode with the parameter autoclose: true, there are two undesired behaviors that occur: After closing the picker, tabbing into the next field causes you to start at the beginning of the document again, w ...