Hide a header and bring it back after a 2-second delay

I REPLIED BELOW

Is there a way to make the header of my webpage fade out when scrolled and then be hidden using style.display? Here's what I have so far:

<script type="text/javascript>

function Scroll()
    {
        var head = document.getElementById('header')
        if (window.pageYOffset > 1) 
            {
                head.style.display = "none";
                head.style.opacity = "0";
            } else {
                head.style.display = "block";
                head.style.opacity = "1";
            }
    }
window.addEventListener("scroll",Scroll);

</script>

I'm unsure how to include a 2-second delay before executing

document.getElementById('header').style.display = "none"
.

I've set up a fade-out animation in the <style> tag using .opacity, but I just need help with the .display delay.

I'd prefer to stick to HTML, JavaScript, or CSS as I'm not familiar with JQuery or other external libraries. Thanks for your understanding! (I'm still learning)

Answer №1

If you want to execute something after a 2-second delay

To achieve this, you can utilize the setInterval or setTimeout functions based on your requirements.

setTimeout(function(){ alert("This message appears after waiting for 3 seconds"); }, 3000);

setInterval: Executes at regular intervals specified by you.

setTimeout: Executes only once after the specified wait time.

W3CSchool Documentation

If you need to wait until the DOM is fully loaded

In such cases, you should monitor the DOMContentLoaded event and ensure that all relevant code is enclosed within it.

document.addEventListener("DOMContentLoaded", function (event) {
function AdjustHeader()
{
    var header = document.getElementById('header');
    if (window.pageYOffset > 1) {
        header.style.display = "none";
        header.style.opacity = "0";
    } else {
        header.style.display = "block";
        header.style.opacity = "1";
    }
}
window.addEventListener("scroll", AdjustHeader);
}

I trust this resolves any issues you were facing.

Answer №2

An effective strategy for optimizing performance and ease of maintenance is to leverage CSS for handling animations while using JavaScript solely for event capture and class addition.

Additionally, it's crucial to ensure that the function linked to the scroll event executes just once.

For element destruction, employing JavaScript to detect the 'animationend' event (its name may vary across browsers) and triggering the elimination process at that point, rather than relying on a fixed 2-second delay, is recommended.

You can view a demonstration of this implementation on Codepen: http://codepen.io/anon/pen/NdWGqO

Below are snippets of the relevant JavaScript and CSS:

// JS
var header = document.getElementById('header');
var hasScrolled = false;

function onScroll() {
    if (!hasScrolled) {
        header.className += " fade-out";
        window.removeEventListener("scroll", onScroll); 
    }
    hasScrolled = true;
}

function destroyElement() {
    header.className += " hidden"; 
}

function captureEvents() {
    window.addEventListener("scroll", onScroll);

    header.addEventListener("animationend", destroyElement);
    header.addEventListener("webkitAnimationEnd", destroyElement);
    header.addEventListener("oanimationend", destroyElement);
    header.addEventListener("MSAnimationEnd", destroyElement);
}

document.addEventListener("DOMContentLoaded", captureEvents);

// CSS

.hidden {
  display: none;
}

.fade-out {
  animation-name: fadeOut;
  animation-duration: 4s;
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
  -webkit-animation-name: fadeOut;
  -webkit-animation-duration: 4s;
  -webkit-animation-iteration-count: 1;
  -webkit-animation-fill-mode: forwards;
}

@keyframes fadeOut {
    from {opacity: 1; }
    to {opacity: 0; }
}

@-webkit-keyframes fadeOut {
    from {opacity: 1; }
    to {opacity: 0; }
}

Answer №3

After some troubleshooting, I managed to solve the issue with the JavaScript code:

<script type="text/javascript">

function Scroll()
{
    var head = document.getElementById('header');
    var timeOut;
    var displayNone = 'head.style.display = "none"'
    if (window.pageYOffset < 1)
        {
            clearTimeout(timeOut);
        }
    if (window.pageYOffset > 1) 
        {
            timeOut = setTimeout(function(){displayNone}, 2000);
            head.style.opacity = "0";
        } else {
            head.style.display = "block";
            head.style.opacity = "1";
            stopcount();
        }
}

window.addEventListener("scroll",Scroll);

For styling in CSS, include the following:

    #header
    {
        height: 100px;
        width: 100%;
        position: fixed;
        background:radial-gradient(circle,#777,#666);
        transition:all 0.2s;
    }

Lastly, in HTML:

<header id="header"></header> /* Insert header information here */

I'm not entirely sure why assigning the "display none" part to a variable resolved the issue.

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 for changing the font size of labels in a tree view using Material UI

While working with material ui treeview, I have customized the fontSize for each treeItem as shown below: <TreeItem key={mainCategory.name} nodeId={mainCategory.name} label={mainCategory.name} disabled={ ...

What is the method for obtaining the size of a mesh object in pixels (instead of Vector3) within BabylonJS?

Exploring Babylon.js How can I retrieve the size of a mesh object in pixels instead of Vector3 in a React application using Babylonjs? This is what I attempted: let meshPixelSize = meshObject.getBoundingInfo().boundingBox; ...

Design a progress bar that advances in increments of at least two and up to a maximum of

My task involves managing a simple list. const [progressBar, setProgressBar] = useState([ { isActive: false, name: "step1" }, { isActive: false, name: "step2" }, { isActive: false, name: "step3" }, { isActive ...

Smooth animation is not being achieved with the Jquery dlmenu

I have implemented a multi-level navigation menu using a demo of the jquery dlmenu plugin v1.0.2. Although most of the functions are working smoothly, the CSS3 menu navigation lacks the fluidity of the jQuery left/right sliding effect. Is there a way to ...

NodeJS: Speed up your workflow by compressing video files

In my quest to enhance the performance of my application, I am seeking ways to compress images and videos to their smallest possible size without sacrificing quality. This process is known as lossless compression. While the imagemin package has proven eff ...

The email validation UI dialog is failing to display any dialog

<html> <head> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"& ...

Debugging a node.js application remotely using SAP Cloud Foundry

Having successfully deployed multiple node.js express services on SAP Cloud Foundry, we have encountered a roadblock in the form of remote debugging. Recognizing that others may be facing similar challenges, we are putting forth a direct inquiry: What is ...

How can I show a "buffering" message in jPlayer?

I need assistance with jPlayer. Here is the code I am using: $("#jquery_jplayer_1").jPlayer({ ready: function () { $(this).jPlayer("setMedia", { title: "Alin", artist: "song", mp3: "utl" ...

What could be causing my controller to show {{message}} instead of the message that was set up in the configuration

<!DOCTYPE html> <html> <head> <script src="js/angular.js"></script> <script src="js/Script.js"></script> </head> <body ng-app="LoginPage" ng-controller = "LoginPageController"> <form ...

Tips for accessing req.fields variables while utilizing Express-Formidable

For some reason, I am encountering difficulties when trying to access variables parsed within req.fields using Express-Formidable. Upon executing a console.log() of req.fields, the output is as follows: { 'registration[username]': '1', ...

Struggling with implementing nested for loops

I am struggling to find a solution for this issue. I need to compare the content of two arrays with each other. If they are exactly the same, I want to execute the if statement; otherwise, I want the else statement to be executed. The current setup is ca ...

Navigating to native script, the method for extracting an ID from a link is revealed

Is there a way to extract the unique identifier from this URL: I want to retrieve the code "11E89887FABBC1D" when clicking on the link. Any suggestions? ...

Using ASP.NET MVC 6 Web API along with Angular, a resource can be posted as an object property in the

I am facing a challenge in sending a complex object from Angular to my web API. Here is how the object looks: { Name: "test", Tax: 23, Addresses: [ { country: "ro", city: "bucharest" }, { country: "fr", ...

Tips for adjusting the thickness of the next/prev icons in the Bootstrap carousel

Exploring the world of HTML/CSS and Bootstrap. There's a carousel with these previous/next buttons : <button class="carousel-control-prev" type="button" data-bs-target="#testimonials-carousel" data-bs-slide="prev ...

Is there a way to align my two tables next to each other using CSS?

.page { display: grid; grid-template-columns: 1fr 1fr; grid-gap: 20px; } .items { float: left; } .secondItem { vertical-align: text-top; float: right; } .page-header table, th, td { border: 1px solid; display: block; background-color: ...

Using Vue along with bootstrap-vue: Ensuring only one list element is expanded in a list (v-for) at any given time

In my Vue project with bootstrap-vue, I am utilizing the b-collapse feature within a v-for loop for lists. While it is functioning correctly, I am struggling to automatically close expanded list elements when a new one is clicked. Here is my question: Ho ...

Adaptable design tailored for smartphones

When it comes to developing mobile websites for various platforms such as iPhone 3 and 4, Android, Blackberry Torch, etc., I usually find myself needing to slice images based on the specific platform. The challenge arises from constantly having to slice im ...

Incorporate a CSS class name with a TypeScript property in Angular version 7

Struggling with something seemingly simple... All I need is for my span tag to take on a class called "store" from a variable in my .ts file: <span [ngClass]="{'flag-icon': true, 'my_property_in_TS': true}"></span> I&apos ...

Having trouble with Jquery and closures or function references?

It seems like the issue is related to a function running in a different scope where the jQuery library is not accessible. This can be seen when the function is called as the last parameter on the second line below. var funcExpandHeight = container.animate ...

What is the best way to apply a class to a jQuery element only if a specific condition is met, and then remove it if the condition is no longer

Is there a more concise method to accomplish the same task? const selectAllCheckbox = $("input.select_all"); const isChecked = selectAllCheckbox.prop("checked"); isChecked ? selectAllCheckbox.parent().addClass("selected") : selectAllCheckbox.parent().r ...