Using Intersection Observer to ensure that text appears instantly on the screen without any fading effect

I'm currently implementing intersection observer to achieve lazy loading for both text and images. In this particular query, I am only focusing on the text aspect of it. The idea is for the text to smoothly transition from 0 opacity to 1 opacity once it comes into view. Specifically, the text should become visible when at least 50% of it is within the viewport of the document. Although the intersection observer is meant to handle this functionality, there seems to be a slight issue with the transition, as if the opacity change isn't triggered by (transform: opacity 3s). Appreciate any help in advance.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css2?family=Mynerve&family=Nunito&family=Open+Sans&display=swap" rel="stylesheet">
    <title>Trelp</title>
</head>
<body>
    <div class="container">
        <header class='header'>
        <img src="images/bgImage.png" alt="Not Loading..." class="bgImage">
        <div class="bgImageScreen"></div>
        <img src="images/logo.png" alt="Not Loading..." class="logo" width="150px" height="40px">
        <div class="title">Build Your<br>Business</div>
        <div class="subText">Work with experts to create and grow<br>your business.</div>
        <a href=""><div class="learnMore"><h3>Learn More</h3></div></a>
        </header>
        <section class="section">
            <div class="businessTitle hidden">80% of Business Fail</div>
            <div class="businessText hidden">Start up businesses fail all around the world. 
                The majority of times, the business lacks funding, market research, and is poorly planned. 
                Failure could also stem from the founder having unrealistic expectations about the future of the Business. 
                This has become an issue, for businesses drive economic growth.
                Here at Trelp, we've addressed this issue, and have found a perfect solution. 
                </div>
            <img src="images/business.png" alt="Not Loading..." class="businessImage"> 
        </section>
    </div>
    <script defer src="script.js"></script>
</body>
</html>

CSS


body {
    margin: 0px;
    padding: 0px;
}


a {
    text-decoration: none;
}

:root {
    --black: rgb(0, 0, 0);
    --white: rgb(255, 255, 255);
}

.container {
    margin: 0px;
    padding: 0px;
    overflow-y: auto;
    overflow-x: hidden;
    height: 100vh;
    width: 100%;
    perspective: 10px;
    scroll-behavior: smooth;
}

.bgImage {
    width: 100%;
    height: 100vh;
    object-fit: cover;
    transform: translateZ(-10px) scale(2);
}

.bgImageScreen {
    position: relative;
    bottom: 102%;
    width: 100%;
    height: 102%;
    object-fit: cover;
    background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.626), black);
    transform: translateZ(-10px) scale(2);
}

header {
    position: relative;
    height: 100%;
    transform-style: preserve-3d;
    z-index: -1;
}

.logo {
    margin: 20px;
    position: relative;
    bottom: 1470px;
    z-index: 3;
}

.title {
    color: var(--white);
    font-family: 'Open Sans', sans-serif;
    font-size: 90px;
    position: relative;
    bottom: 1400px;
    left: 120px;
    line-height: 100px;
    margin-bottom: 30px;
}

.subText {
    color: var(--white);
    font-family: 'Open Sans', sans-serif;
    font-size: 30px;
    position: relative;
    bottom: 1400px;
    left: 120px;
}

.learnMore {
    width: 180px;
    height: 70px;
    position: relative;
    bottom: 1400px;
    left: 120px;
    font-size: 20px;
    font-family: 'Open Sans', sans-serif;
    margin-top: 30px;
    border: 3px solid var(--white);
    background-color: var(--white);
    color: var(--black);
    border-radius: 15px;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 1s;
}

.learnMore:hover {
    color: var(--white);
    background-color: transparent;
}

.section {
    width: 100%;
    height: 150vh;
    background: var(--black);
    margin: 0px;
    position: relative;
    bottom: 27px;
}

.hidden {
    opacity: 0;
    transform: opacity 3s;
}

.show {
    opacity: 1;
}

.businessImage {
    position: relative;
    bottom: 400px;
    left: 750px;
    border-radius: 20px;
}

.businessTitle {
    color: green;
    font-family: 'Nunito';
    font-size: 40px;
    position: relative;
    top: 150px;
    left: 150px;
    margin: 30px;
    width: 500px;
}

.businessText {
    color: green;
    font-family: 'Nunito';
    font-size: 25px;
    width: 500px;
    position: relative;
    top: 150px;
    left: 150px;
    line-height: 40px;
    margin: 30px;
}

Javascript


const observer = new IntersectionObserver(entries => {
    entries.forEach(entry => {
        if (entry.intersectionRatio >= 0.5) {
            entry.target.classList.add('show')
        } else {
            entry.target.classList.remove('show')
        }
    }) 
}, {threshold: [0.5]})

const hiddenElement = document.querySelectorAll('.hidden')
hiddenElement.forEach(el => observer.observe(el))

Answer №1

It seems like you intended to use transition: opacity 3s rather than transform: opacity 3s in the .hidden rule:

const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.intersectionRatio >= 0.5) {
      entry.target.classList.add('show')
    } else {
      entry.target.classList.remove('show')
    }
  })
}, {
  threshold: [0.5]
})

const hiddenElement = document.querySelectorAll('.hidden')
hiddenElement.forEach(el => observer.observe(el))
// CSS styles here...
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://fonts.googleapis.com/css2?family=Mynerve&family=Nunito&family=Open+Sans&display=swap" rel="stylesheet">
  <title>Trelp</title>
</head>

<body>
  <div class="container">
    // HTML content here...
  </div>
  <script defer src="script.js"></script>
</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

When clicked, the onClick feature will reduce the number each time instead of initiating the timer

Currently, I am working on a meditation application using React. As a starting point, I implemented a 25-minute countdown feature. The challenge I am facing is that the timer starts counting down each time the button is clicked, rather than triggering it ...

JavaScript code for validating two passwords is malfunctioning

I'm currently working on a registration form for my website and I'm trying to implement a JS script that compares two password inputs (password and repeat password) and displays a message saying "passwords are not the same." Below is the code I h ...

JQM activates upon the creation event

In order to refresh the DOM layout, I manually trigger the 'create' event using the following jQuery syntax: $(elem).trigger('create') Now, I am looking for a way to execute a callback function when the page has finished refreshing. I ...

Altering the status of a property in an object, at a specific position within a collection of objects, contained within another object?

Currently using React and having some trouble with the setState hook to update a value deep within an object structure ...

Exploring the functionality of the JavaScript switch statement across various condition scenarios

switch (true) { case (angle<20): console.log("case1") break; case (angle<70): console.log("case2") break; case (angle< ...

Using Three.js to create a React button positioned above a canvas

Here's the code I have written using three.js in a React component. I am looking to add a button above the canvas. How can I achieve this? Additionally, I would like to know how to add a click event on objects rendered in three.js. import React, { Com ...

Tips for transferring the content of a variable to a handlebars block

Currently, I am grappling with HTML code that involves handlebars templates to store internal variables. While I may not be an expert in handlebars, I am trying my best to navigate through it. The crux of my issue lies in the need to access a lengthy list ...

What are the steps to make a basic slider with jQuery without using plugins?

<script> const animateImages = function(){ $("#slider").animate({"left":"-=1775px"},10000,function(){ $("#slider").animate({"left":"0px"},10000); animateImages(); }); }; animateImages(); </script> I incor ...

Display various sets of data from multiple models within a single view

My project is focused on Asp.net Mvc and I am encountering a challenge in displaying multiple model data in one view. However, I do not want to showcase it in a list or grid format, instead, I prefer a Form View style. The two modal classes involved are Pr ...

Is the background color extending the entire width of the page?

Hey there, I'm currently trying to determine how to set the background-color on a paragraph or h1 so that it only appears behind the words and not across the entire page with blank space. I'm still a beginner when it comes to coding. I'm wor ...

Learning the process of accessing a JSON file from a different directory

I am faced with a straightforward folder structure, it looks like this: project │ └───data │ file.json │ └───js test.js My goal is to access the content of file.json within the test.js file in order to perform some ...

The app's functionality is disrupted by a malfunctioning Appframework jQuery

Having some trouble implementing the jQuery UI autocomplete widget in a PhoneGap app using the jq.appframework.js plugin. Here is how I have included the necessary scripts and styles: <script src="appframework/jquery.js"></script> <script s ...

The issue of ERR_MODULE_NOT_FOUND in Node.js express.Router arises when attempting to import new routes

Something strange is happening. I was in the process of organizing my routes by creating a new folder. Within this folder, I used the express.Router API to define the routes and then exported the router itself. Here is an example code snippet from my pos ...

React - error caused by an invalid hook call. Uncaught Error: React encountered a minified error with code #

My goal is to incorporate the micro-frontend concept by implementing various react apps. Container Header Dashboard All three are separate applications. I intend to utilize the Header and Dashboard apps within the Container app. For the Header app, it& ...

How can I globally assign a JavaScript variable based on an AJAX response?

Here is the ajax code I have: <script> $('a[data-id]').click(function () { var id = $(this).attr('data-id'); var domain = $(this).attr('data-domain'); $.ajax({ url: 'getdata& ...

Troubleshooting issues with jQuery `.live()` event not triggering as expected

In a project I am working on, I have implemented complex AJAX functionality to fetch inner page content from a WordPress blog. Due to the dynamic nature of the site, where the DOM is replaced after page load via AJAX, I have opted to use jQuery's .liv ...

Whenever I try to upload a file using ajax in MVC, I consistently encounter a null Request.Files in action side

I am facing an issue with uploading an image using ajax mode in MVC. I have tried a method where everything seems to work fine in the JavaScript code - it gets the formdata and sends the ajax request to the controller correctly. However, in my controller, ...

Guide to setting up Date Range Validator within MVC 4

Is there a way to limit the user from inputting a date outside of a specific range in my MVC 4 application? I'd appreciate any advice on how to achieve this. ...

The error message "TypeError: res.json is not a function in express.router" indicates that

I encountered the following error message and I'm not sure how to resolve it: TypeError: res.json is not a function I have reviewed the express documentation but couldn't find any syntax errors or issues. Here is my code: index.js import expr ...

Guidelines for dynamically switching between two buttons (function/text) depending on an external factor (such as the number of items bought)

I'm exploring a previous concept of toggling between two buttons conditionally in a CRA. import ... const ... export const Index = () => { // Setting up boolean state to toggle buttons conditionally const [reachMax] = React.useState(id <= ...