Tips for concealing a div upon reaching a specific scroll point, even with varying content sizes

Hey there! I am completely new to web programming and currently working on a landing page. The challenge I'm facing is that the content in the first column is dynamic, meaning it can vary in length.

I'm looking for a way to hide my call-to-action button once a user reaches the author info section on the page. Any guidance or assistance on how to achieve this would be greatly appreciated. Thank you!

https://i.sstatic.net/WyQRU.png

Below are the snippets of my code:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Test Scroll</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <style>
    .cta{
        position:sticky;
        top:600px
    }
  </style>
</head>
<body>

<div class="jumbotron text-center">
  <h1>Hide a div after regular amount of scroll</h1>
  <p>Resize this responsive page to see the effect!</p> 
</div>
  
...

Even though I attempted to implement a solution using JavaScript, the scroll amount remains undefined due to the variable content length. Here's what I've tried:

<script>

$(document).scroll(function () {
    var y = $(this).scrollTop();
    if (y > 900 && y < 1200) {
        $('.cta').fadeIn();
    } else {
        $('.cta').fadeOut();
    }

});

</script>

Answer №1

If you're looking for a solution to hide content based on visibility, consider using the jQuery Visible plugin. By implementing a simple script, you can control when certain elements are displayed based on user scroll behavior. This approach allows you to hide article content once author information becomes visible on the screen, providing a seamless reading experience.

$(document).scroll(function() {
  if ($('.author-info').visible(true)){
   $('.article-content').hide();
  } else {
    $('.article-content').show();
  }
});

(function($) {

  /**
   * Copyright 2012, Digital Fusion
   * Licensed under the MIT license.
   * http://teamdf.com/jquery-plugins/license/
   *
   * @author Sam Sehnert
   * @desc A small plugin that checks whether elements are within
   *         the user visible viewport of a web browser.
   *         only accounts for vertical position, not horizontal.
   */
  $.fn.visible = function(partial) {

    var $t = $(this),
      $w = $(window),
      viewTop = $w.scrollTop(),
      viewBottom = viewTop + $w.height(),
      _top = $t.offset().top,
      _bottom = _top + $t.height(),
      compareTop = partial === true ? _bottom : _top,
      compareBottom = partial === true ? _top : _bottom;

    return ((compareBottom <= viewBottom) && (compareTop >= viewTop));
  };

})(jQuery);
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Test Scroll</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <style>
    .cta {
      position: sticky;
      top: 600px
    }
  </style>
</head>

<body>

  <div class="jumbotron text-center">
    <h1>Hide a div after regular amount of scroll</h1>
    <p>Resize this responsive page to see the effect!</p>
  </div>
  <div style="height:200px">
    
  </div>

  <div class="container">
    <div class="row">
      <div class="col-sm-8">
        <div class="article-content">
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
          in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
          <br/> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
          aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
          <br/> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
          aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

          <br/> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
          aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        </div>
      </div>
      <div class="col-sm-4">
        <div class="cta bg-dark py-5 text-light text-center">
          subscribe our newsletter
        </div>
      </div>

    </div>
  </div>


  <div class="container author-info">
    <div class="row">
      <div class="col-sm-12 py-3">
        <div><strong>Author name</strong></div>
        <div class="py-2"><strong>Author info:</strong> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
          commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div>
      </div>

    </div>

  </div>
</body>

</html>

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

What is the best way to automatically assign a class attribute to all form widgets in Django?

Whenever I create a form using Django, I want the input tag to automatically include a specific CSS class (form-control). Currently, I have to manually add lines of code in my forms.py file for each field like this: class InsertItem(forms.ModelForm): ...

Spin an icon when the Button it is inside of is clicked

I am currently using a Material-UI button with the following code: <Button disableFocusRipple={true} disableRipple={true} color="inherit" onClick={openBlogMenu} className={classes.blogButtonStyle} > <LibraryBooksIcon /> Blog {! ...

The property 'x' cannot be found when declaring two different return types

Consider this example: interface Dog { name: string } const likeDog = true const getDog = (): Dog | boolean => { const val = likeDog ? { name: 'fido' } : false return val } const myComponent = (): void => { const dog = getDog() ...

Is it valid JSON to have values such as "ok", false, true, null, and 123?

Can the following strings be considered valid JSON? "ok" false true null 123 If not, why does the standard JavaScript JSON.parse method allow these values to be used as valid JSON? I have encountered issues when using these values in JSON REST APIs, ...

Storing a function in local storage using Javascript

Is there a way to save this information in local storage, or is there an alternative method for storing it? $('#pass_to_score').on('click',function(){ var compressed = function(){ $('.whole_wrap_of_editcriteria').css(&ap ...

Having trouble incorporating a bootstrap template into my Angular project: Whenever I add the styling files, the application ceases to function

I'm currently working on incorporating a Bootstrap template into my Angular project, which already utilizes Bootstrap. Check out my Angular project https://i.sstatic.net/SKzRk.png. Now, I'm focusing on integrating the "Ethereal" scrolling templa ...

Numerous anchor links are present

Is it possible to eliminate the red lines between "google links" while keeping the border color as red? How can I achieve this? Here is the code snippet provided: <!doctype html> <html> <head> <title>Website</title> </he ...

What is the best way to receive detailed error messages from the LESS compiler when using it in Symfony 2?

I have successfully implemented dynamic compilation of LESS scripts to CSS in Symfony 2 by following this guide: However, I am facing an issue where if there is an error in a LESS script, the compilation fails and no CSS is generated for the browser. Is t ...

Is there a way for me to directly download the PDF from the API using Angular?

I'm trying to download a PDF from an API using Angular. Here's the service I've created to make the API call: getPDF(id:any) { return this.http.get( `url?=${id}`, { responseType: 'blob' as 'json', obs ...

What is the Vue.js alternative to setTimeout?

I'm currently in the process of developing a shopping cart feature using Laravel and Vue. In my system, when an item is added to the shopping basket, I want to display a confirmation message by toggling a Vue variable that is being monitored through a ...

What is the appropriate title for the css class?

When creating a stylesheet for a website, should the CSS style names be related to the website or its content? For example, if my website is about web development, would it be correct to use style names like: #web-development-header .web-development-comp ...

Creating a triangle shape using Bootstrap to style a div element, similar to the image provided

Trying to achieve the look of the attached image with a few divs. I know I can use a background image like this: background:url(image.png) no-repeat left top; But I'm curious if there's another way to achieve this without using a background ima ...

The JQuery parseFloat() function seems to be consistently returning "NAN" whenever it is used with the .text property

I am currently encountering an issue with parsing the text property of an input element identified by the id currency-converter. My goal is to convert this text into a floating-point value so that I can proceed with applying mathematical operations to conv ...

Performing a Node.js and Mongoose query to match an ID with values that are stored as a string separated by

Exploring the realms of Mongoose and NodeJS is a new venture for me. Within my product document, I am storing category ids in the following format: "reviewscount" : "2", "overallrating" : "4.5", "urlkey" : "strive-shoulder-pack", "productid" : "2", "cate ...

The versatility of Node.js' hbs module as an engine

Recently diving into the world of node js, I stumbled upon the hbs module. In this code snippet below: app.set('view engine', 'html'); app.engine('html', require('hbs').__express); I'm curious to know more abo ...

Utilizing the power of Datatables through AJAX calls with HTML Forms

Hello, I am currently working on incorporating djangorestframework-datatables with the datatables' JQuery plugin. My task involves loading a large table (consisting of approximately 15000 entries, paginated) with the serverSide option enabled. Enabli ...

Is there a way to use Css Autoprefixer on multiple files at once with a single function

My project built with Angular2 contains over 100 CSS files that do not have any prefixes for browsers like Mozilla or Chrome. I am looking for a tool, gulp task, or anything else that can automatically add prefixes to all of my CSS files. I attempted to u ...

Combining Applet with Microsoft Access

This is a more specific version of my original inquiry. I have successfully created an applet that should interact with my MS Access database. It runs smoothly through a compiler, but when I embed the .class file in an html page and open it, the applet run ...

Experiencing difficulties with ng-modal in the controller invocation

These are the steps I followed: 1) First, I downloaded the script file from: https://github.com/doodeec/dcom-angular-dialog 2) Next, I included it in both my webpage and application: var summariesApp = angular.module('summariesApp', ['ui ...

Identifying the server control ID on the master page with the help of jQuery

My Asp.net Master Page includes an adrotator element. <asp:AdRotator ID="adr" AdvertisementFile="~/Adrotator.xml" Width="180px" Height="200px" runat="server" Target="_self" /> I have implemented a jquery script to rotate the ADS, b ...