Conceal the div once it reaches the top of the webpage

Is there a way to hide an "h1" element when its parent div reaches the top of the page and then show it again when it moves down using both JQuery and CSS? I attempted to utilize a scroll listener in JQuery to toggle a class, but this resulted in the "h1" element quickly toggling between classes. How can I successfully hide the div when it reaches the top of the page and display it again once it starts moving down?

$(function() {
  $(document).scroll(function() {
    var distance_from_top = $("#backgroundtitle h1").offset().top;
    if (($(window)).scrollTop() > distance_from_top) {
      $("#backgroundtitle h1").toggleClass("hidetitle");
    }
    if (($(window)).scrollTop() < distance_from_top) {
      $("#backgroundtitle h1").toggleClass("hidetitle");
    }
  });
});
@charset "utf-8";
 html {
  height: 100%;
  margin: 0;
  font-family: "Myriad Set Pro", "Lucida Grande", "Helvetica Neue", "Helvetica", "Arial", "Verdana", "sans-serif";
}
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
a {
  text-decoration: none;
}
#header {
  width: 100%;
  height: 50px;
  background: rgba(0, 0, 0, 0.5);
  z-index: 100;
  line-height: 50px;
  position: fixed;
  top: 0;
}
#header {
  margin: 0 auto;
  display: block;
}
#header ul {
  list-style-type: none;
  margin: 0;
  text-align: center;
  padding: 0;
}
#header ul li {
  display: inline;
  text-align: center;
}
#header a {
  color: #FFFFFF;
  padding: 0 5%;
  margin: 0;
  text-align: center;
}
#homeimage {
  background: url(Images/Home_Image.jpg) no-repeat center center;
  background-size: cover;
  height: 100%;
  position: relative;
  top: 0;
  z-index: -100;
  width: 100%;
  display: block;
}
#background {
  width: 100%;
  height: 100%;
  line-height: 100%;
  text-align: center;
  display: table;
  background: rgba(0, 0, 0, 0.2)
}
#background h1 {
  display: table-cell;
  vertical-align: middle;
  font-size: 100px;
  color: #FFFFFF;
  font-weight: 100;
}
#backgroundtitle {
  margin: 0 auto;
  display: table-cell;
  vertical-align: middle;
}
#backgroundtitle h1 {
  font-size: 100px;
  color: #FFFFFF;
  font-weight: 100;
  text-align: center;
  display: inline;
  padding: 0;
  margin: 0;
}
#container1 {
  height: auto;
  background-color: #00A3FF;
  overflow: hidden;
}
#container1 h1 {
  padding: 0;
  padding-top: 5%;
  margin: 0;
  color: #FFFFFF;
  text-align: center;
}
#container1text {
  width: 50%;
  padding: 2.5%;
  float: left;
}
#container1text p {
  font-size: large;
}
<body>
  <div id="header">
    <ul>
      <li><a href="#homeimage">Home</a>
      </li>
      <li><a href="#container1">Introduction</a>
      </li>
    </ul>
  </div>
  <div id="homeimage">
    <div id="background">
      <div id="backgroundtitle">
        <h1>Title</h1>
      </div>
    </div>
  </div>
  <div id="container1">
    <h1>Introduction</h1>
    <div id="container1text">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores, cumque, id, quasi iste illum dolorum libero vero voluptate labore ullam voluptatum aliquam tempore dolor molestiae debitis hic ipsam vel quidem.</p>
      <br>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Harum, dignissimos magni nulla cupiditate nisi veritatis hic ullam saepe dolor numquam recusandae assumenda aspernatur perspiciatis non similique ipsam architecto sapiente excepturi!</p>
      <br>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis, ducimus, atque, delectus, fugiat adipisci animi deserunt culpa doloremque ea impedit natus dolores amet veniam vitae eaque eligendi fugit dolorum hic!</p>
    </div>
  </div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №1

The issue at hand arises from the lack of a check to see if the h1 element contains the hidetitle class before toggling. This results in the class toggling with every scroll action. The revised code snippet below addresses this by verifying both the position of the element and the presence of the hidetitle class before toggling:

$(function() {
    $(document).scroll(function() {
        var h1selector = $("#backgroundtitle h1");
        var distance_from_top = h1selector.offset().top;

        if(($(window)).scrollTop() > distance_from_top && h1selector.hasClass("hidetitle")) {
            h1selector.toggleClass("hidetitle");
        }
        else if($(window)).scrollTop() < distance_from_top && !h1selector.hasClass("hidetitle")){
            h1selector.toggleClass("hidetitle");
        }
    });
});

Answer №2

A recommended approach for handling this type of situation would be using addClass() and removeClass().
1. Give an id to your title, for example: id="title" 2. Define the CSS styling in a way that #title.hideTitle{display:none;} will take precedence over other rules.
3. Implement the following JavaScript code:

<script>
$(document).ready(function(){
  $(document).scroll(function() {
      if($(window).scrollTop() > 301) {
          $("#backgroundtitle h1").addClass("hideTitle");
      }else{
        $("#backgroundtitle h1").removeClass("hideTitle");
      }
  });
});
</script>

Feel free to share your thoughts on this approach ;-)

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

Invoke a codebehind function using jQuery

I am encountering an issue while trying to complete a simple task. I am attempting to pass values to a code behind method, perform some calculations, and then return the result. Initially, I started with a test method but have not been successful in making ...

Assign a value to a locally scoped variable within an iteration in Angular 2

Within my Angular code, I have the following HTML snippet: <span *ngIf="ControllerType?.AttributeID =='Controller Type'"> <select multiple name="ControllerType.Default" [(ngModel)]="Contro ...

Call a function in jQuery from outside

Encountering an issue when trying to call a function from a separate JavaScript file. In the HTML file named "a.html," here is the content: <html> <head> <script src="${resource(dir: 'js/demo', file: '.js')}"></ ...

Unable to locate web element using Selenium in C#

Here is the HTML code I am currently using: <div class="modal-footer"> <button class="btn btn-primary" type="button" value="Show Alert" ng-click="questions.getIrMessage()" data-dismiss="modal">Confirm</button> <button class ...

Is it possible to establish a standard view for the date/time input field, disregarding the user's

When working with a Django Form, I am incorporating a datepicker. While the solution may involve JS and HTML, my query remains specific. date_field= forms.DateField( input_formats=['%Y-%m-%d'], widget=forms.DateInput( format=& ...

What is the best way to align this div tag with the right side of the box?

.left { width: 50%; display: inline-block; float: left; } /* Second user block */ .right { border-color: lightskyblue; background-color: darkcyan; width: 50%; ...

Upload file to database and move to new location

In order to gain a clearer understanding, I have a question regarding inserting data from a form. Let's say I have the following form: <form action="upload.php" method="post" enctype="multipart/form-data"> Select image to upload: <inp ...

Retrieving checkbox values from a MySQL database in HTML/PHP

My database contains data stored in varchar format, such as S,M,L,XL. On my PHP page, I have checkboxes corresponding to these options. Is it feasible to fetch this data from the database and display the pre-checked checkboxes in HTML using PHP? (For exa ...

jScrollPane malfunctioning with Bootstrap 3's dropdown menu

I'm attempting to add a vertical scrollbar to a Bootstrap dropdown. Below is the HTML code I'm working with: <div class="btn-group"> <button type="button" class="btn btn-default dropdown-toggle btn_drop_down" data-toggle="dropdown"> ...

Having trouble with jquery's empty() function not functioning as expected

I'm brand new to using jquery so I apologize in advance for any beginner mistakes. Essentially, my issue is straightforward: Here is the HTML code I have: <div class="v" align="center" id="div4"> <div id="div5" class="h blurb"> <sp ...

Seeking assistance in creating custom tabs for integration with a jQuery tabs plugin

Attempting to navigate the world of CSS as a newbie, I find myself struggling with creating tabs. Our current tab setup can be viewed here, but unfortunately, these tabs are created using an unattractive <table> tag. Below is the code responsible fo ...

What specific quirk in Firefox is responsible for this behavior, and is there a way to replicate it in standards mode?

In Firefox, this particular document displays differently in standards mode compared to quirks mode. When in quirks mode, the div fills the entire screen, but in standards mode it does not. I went through the MDN quirks list and couldn't pinpoint a sp ...

Overflow of content within a rectangular element

One challenge I'm facing is creating HTML/CSS code that automatically adjusts the website layout (blocks and content) when I resize the browser window. For example: I encounter text overflow issues in a block I've created when I minimize the brow ...

Simple method for validating a text box field using jQuery without the need for a form

I am looking for a way to activate jquery unobtrusive validation without a form using the specified pattern: <script type="text/javascript"> $('.btnAddAsync').click(function (e) { e.preventDefault(); // Avoid href p ...

The search for 'post_sharing' with parameters ('',) did not yield any results. No matching patterns were found

Whenever I try to click on the option Share this Post in show_more.html, I encounter an error. show_more.html <p> <a href="{% url 'mains:post_share' post.id %}">Share This Post</a> </p> urls.py path('< ...

What is the best way to extract the event time when a user clicks on an event in fullcalendar?

Is there a way to extract only the time from an eventclick event in fullcalendar? Currently, I am receiving details about the event including date and time. How can I specifically retrieve just the time (e.g. 6:00:00 am)? You can find the code snippet tha ...

What is the best way to adjust the size of a background image on Safari

Using Chrome When using Chrome, the functionality is just like what's depicted in the image above. However, when using Safari The issue arises, as it does not work as expected in Safari. See below for the CSS code: background-image: url(r ...

Navigate through each element with a specific class name in a block of HTML code using

Currently, I am dealing with an HTML string that is being retrieved through AJAX. Let's assume it looks like this: var htmlString = '<div class="post"></div><div class="post"></div>'; I want to find a way to iterat ...

a pair of browser windows displaying a web application built with ASP.NET MVC

We are currently in the process of developing an ASP.NET MVC web application for internal use within our organization. Our users' productivity can greatly benefit from having a larger screen space, which is why we have decided to provide each user wit ...

Leveraging JSON data to dynamically create HTML elements with multiple class names and unique IDs, all achieved without relying on

Recently, I've been working on creating a virtual Rubik's cube using only JS and CSS on CodePen. Despite my limited experience of coding for less than 3 months, with just under a month focusing on JS, I have managed to develop two versions so far ...