Is there a way to adjust the height pixel value in my code so it can be dynamic?

I have created a simple script that allows selected objects to fade in as the user scrolls down. However, my issue is that this script is quite rigid. If I were to apply it to 20 different objects, for example, I would need to manually adjust the height each time. Here is an illustration of this:

$(document).ready(function () {
  $(window).scroll(function () {
    if ($(this).scrollTop() > 500) {
      $(".header-js-scroll-fade").css({"opacity" : "1"});
      $(".home-vorteile").addClass("header-img-fade-in-by-scroll");
    }
    else {
      $(".header-js-scroll-fade").css({"opacity" : "0"});
      $(".home-vorteile").removeClass("header-img-fade-in-by-scroll");
    }
  });
});
.header-js-scroll-fade {
opacity: 0;
transition: 0.5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 id="vorteile-text">Building Trust Through,</h1>

<section class="home-vorteile">
  <div class="header-js-scroll-fade header-img-fade-in-by-scroll">
    <img src="https://via.placeholder.com/500" />
    <h2>Security.</h2>
  </div>
  <div class="header-js-scroll-fade header-img-fade-in-by-scroll">
    <img src="https://via.placeholder.com/500" />
    <h2>Latest AI Technology.</h2>
  </div>
  <div class="header-js-scroll-fade header-img-fade-in-by-scroll">
    <img src="https://via.placeholder.com/500" />
    <h2>Premium Materials.</h2>
  </div>
</section>

Answer №1

This script determines if the element is within the viewport of the user, adding a specific class if it is visible and removing it if it's not. To apply this functionality to any element, simply add the class header-js-scroll-fade.

The isInViewport function was created by Tom Pažourek and can be found here:

// https://stackoverflow.com/a/40658647/8605830
$.fn.isInViewport = function() {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();

    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(document).ready(function () {

  $(window).scroll(function () {
  
    $('.header-js-scroll-fade').each(function () {
      if ($(this).isInViewport()) {
        $(this).addClass("visible");
      }
      else {
        $(this).removeClass("visible");
      }
      
    });
    
  });
  
});
.header-js-scroll-fade {
opacity: 0;
transition: 0.5s;
}

.header-js-scroll-fade.visible {
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 id="vorteile-text">Vertrauen durch,</h1>

<section class="home-vorteile">
  <div class="header-js-scroll-fade">
    <img src="https://via.placeholder.com/500" />
    <h2>Sicherheit.</h2>
  </div>
  <div class="header-js-scroll-fade">
    <img src="https://via.placeholder.com/500" />
    <h2>Neueste KI Technik.</h2>
  </div>
  <div class="header-js-scroll-fade">
    <img src="https://via.placeholder.com/500" />
    <h2>Beste Materialien.</h2>
  </div>
</section>

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 extract text/html that appears between two consecutive <input> tags?

Is there a straightforward method to extract the text or HTML content located between input tags, even though these tags do not require closing tags? For instance, in the example below, I am looking to retrieve <b>Bob and Tim</b><br>Tim & ...

Displaying various images within a bootstrap modal window

I'm facing an issue with my gallery. It contains small images, and when a user clicks on a thumbnail, a modal should open with the full-size image. The problem is that even though I have the full-size images stored in the "/uploads/" folder and the th ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...

What is the best way to obtain the value of a Promise within a function?

When working with Promises, accessing the value inside the .then method is simple. Take a look at this example: const Promise = require("bluebird"); const fs = Promise.promisifyAll(require('fs')); const mergeValues = require('./helper' ...

Comparison of passwords in Nodejs is hindered by Bcryptjs

Struggling to compare passwords using bcryptjs for JWT authentication. Unable to successfully verify the password during login to sign the token and send it to the client. Issue The problem arises when trying to use the .compare() method in bcryptjs and ...

Show only the items in bootstrap-vue b-table when a filter is actively applied

How can I set my bootstrap-vue b-table to only show items when a filter is applied by the user (i.e., entered a value into the input)? For example, if "filteredItems" doesn't exist, then display nothing? This is primarily to prevent rendering all rows ...

Building CSS columns

Similar Inquiry: Creating dual columns in HTML/CSS layout I'm exploring ways to achieve a two-column layout within a wrapping div element. Currently, I have the following CSS code snippet which centers a div inside the browser: .wrapper {width: ...

Unpredictable algorithm for selecting the champion

I manage a website that features promotions and users. Users have the ability to register for these promotions, with one random user selected as the winner. Initially, the formula for selecting the winner was quite simple: $total_users = 100; //total use ...

Utilizing the Model-View-Controller architecture to efficiently transfer a collection

I'm attempting to send an email from my controller after receiving two images from a view. Despite numerous attempts, when I debug the Post method in my controller, the object always contains null values. However, logging the data being sent shows th ...

steps for signing in to garmin account with javascript

Attempting to set up an Oauth1 login for Garmin using Angular2 and standard http calls, but encountering a pre-flight OPTIONS call error on the initial request to oauth/request_token path. It seems like CORS is not enabled or something similar. Has anyone ...

jQuery Toggle and Change Image Src Attribute Issue

After researching and modifying a show/hide jQuery code I discovered, everything is functioning correctly except for the HTML img attribute not being replaced when clicked on. The jQuery code I am using: <script> $(document).ready(function() { ...

What is the best way to extract all <tr> elements from a <tbody> and then convert them into a String?

Below is an example of an HTML table: <table id="persons" border="1"> <thead id="theadID"> <tr> <th>Name</th> <th>sex</th> <th>Message</th> </ ...

Creating interactive forms (the optimal method)

My project involves creating an Android Tablet application that will connect to a web service to retrieve dynamic forms which can be filled offline and then submitted when online. These forms are not predefined, and may contain attached images. However, I ...

Ways to eliminate extra spacing when search bar is expanded

My code is all contained within a header with the class 'example'. When the 'search' button is clicked, a div with the class 'search-bar' appears and its borders match those of the header. However, I want the search bar to ali ...

Error code 8070000c is specific to Uploadify and can only be encountered when using the

Encountered an issue with jQuery uploadify - receiving error message: SCRIPT16389: Could not complete the operation due to error 8070000c. jquery.uploadify.v2.1.4.js, line 292 character 5 This error occurs on the second attempt when using IE browser. Any ...

What is the best way to implement bypassSecurityTrustResourceUrl for all elements within an array?

My challenge is dealing with an array of Google Map Embed API URLs. As I iterate over each item, I need to bind them to the source of an iFrame. I have a solution in mind: constructor(private sanitizer: DomSanitizationService) { this.url = sanitizer. ...

Center div encroaching on floated left div

Can someone help me align three divs horizontally? I'm having an issue where the center div is overlapping the left div. What could be causing this problem? <div> <div style={{width:"100px", border:"solid blue", ...

Can we find a solution to optimize "Crystal Reports" for mobile browsers and make it responsive?

I'm in the process of making my entire Asp.net application responsive for mobile browsers by utilizing Bootstrap. However, I've encountered a challenge with making Crystal Report responsive for mobile browsers. If anyone has any advice on how to ...

Having two owl carousels on one page is causing some issues

Struggling to implement two owl carousels on my page. Gif: View Gif Here The first carousel (shown at the top in the gif) is functioning perfectly. However, the second one (beneath the first in the gif) is not behaving as expected. Instead of displaying ...

Having difficulty retaining the value of a variable following the retrieval of JSON data

For my current project, I am utilizing the highstocks charting library in combination with JQuery. My goal is to create a single chart divided into three sections, each displaying different data sets. To import the data, I have referenced the sample code p ...