Determine whether the element is visible in at least half of the viewport

I am working on a project that involves 4 cards with images. I want the image to animate in from the left when it comes into viewport. I have finalized the CSS for this effect, but the JavaScript code always returns false even when the element is visible on the screen. I specifically want the function to return true when at least half of the image is in the viewport. Despite using a forEach loop to check all images, the function keeps returning false.

Below is the JavaScript code snippet I have developed:

function isInViewport(container) {
  const rect = container.getBoundingClientRect();
  
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

This is the HTML structure I am using:

<div class="col-md-6 col-sm-12 p-0 overflow-hidden bg-dark imageCard">
  <div class="imageCont">
    <img
      src="images/ferrariPhoto1.webp"
      alt=""
      style="width: 100%; height: 100%"
      class="ferrariImageSection"
    />
  </div>
</div>

Answer №1

I created a simple demonstration using your function on codepen, and it appears that the function is performing correctly: https://codepen.io/lukenetsurfer/pen/WNPzQdO

This demo showcases a blue square that can be dragged across the screen. By checking the console, you can observe the output of isInViewport every time the square is moved. When the square is only partially visible (partially off-screen), isInViewport returns false; otherwise, it returns true.

Here are some debugging suggestions to help identify why it may not be working in your case:

  • If you console.log container, does it display the expected value? (Perhaps you are inspecting the wrong element?)
  • If you console.log the values involved in your boolean comparison, do they align with your expectations?

Answer №2

Check out the Intersection Observer as suggested by Darryl Noakes.

I'm unable to provide specific help because the code in the question appears to be incomplete and lacks important details. The sample below showcases the use of IO with detailed comments.

const options = {
  root: null, // Default is null (html/viewport)
  rootMargin: "0px", // Default is 0 - values can be 1 to 4 numbers in px
  threshold: [0.25, 0.75]
  /* Threshold refers to the percentage of target element length that's visible */
};

/** Initialize Observer
 * Pass in callback function and options object.
 */
const observer = new IntersectionObserver(showHideTitle, options);

// Select all elements with class .card
const cards = document.querySelectorAll(".card");

// Apply observer to each .card element
cards.forEach(card => observer.observe(card));

/** Callback Function
 * When a .card is within thresholds (0.25 or 0.75),
 * this function is triggered.
 * Entries contain entry objects associated with target elements (.card).
 * Property .target returns the triggering element.
 * Property .intersectionRatio indicates the % of target element in viewport.
 */
function showHideTitle(entries, observer) {
  entries.forEach((entry) => {
    let text = entry.target.firstElementChild;
    if (entry.intersectionRatio > 0.75) {
      text.classList.add("fade-in");
      text.classList.remove("fade-out");
    } else {
      text.classList.remove("fade-in");
      text.classList.add("fade-out");
    }
  });
}
* {
  margin: 0;
  padding: 0;
}

:root {
  font: 5vmin/1 "Segoe UI";
}

body {
  display: flex;
  /* Other CSS properties removed for brevity */
}

/* Additional CSS styles omitted for clarity */
<ol id="list">
  <li class="card directions">
    <p class="text">Scroll to the right. &gt;</p>
  </li>
  <li class="card">
    <figure>
      <figcaption class="text">Lamborghini</figcaption>
      <img src="https://i.ibb.co/g3MmqLY/car1.png">
    </figure>
  </li>
  <li class="card directionless">>
    <!-- More list items here -->
  </li>
</ol>

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

JavaScript can be used to extract a specific value from a SOAP response

In order to extract the Patient ID (PATAA000000040) from the SOAP response below using JavaScript and insert it into a Mirth destination, we need to target the value under the livingSubjectId tag. It's important to note that this tag may repeat, but w ...

Creating personalized static HTML cards with PHP Mirror API for Google Glass

Looking to integrate an HTML formatted card into Google Glass timeline using the Mirror API. Utilizing the PHP PHP Mirror Client API, which accepts a message and image as parameters, displaying the image in the background similar to this example: insert ...

Is it possible to retrieve only the attributes in an array?

https://i.sstatic.net/E1DMb.png I am working with an array that has properties embedded within it. I am wondering if there is a method to separate out these properties from the array data and transform them into a distinct object containing only the prope ...

jQuery Issue: Submission Count Doubling with Each POST Request

My current issue involves using jQuery to send data to a PHP file, but I've noticed that each time I submit the form, the data gets duplicated. Initially, it posts once when I press the submit button. However, upon returning to update the form and sub ...

I encountered an issue trying to animate an OBJ file in Three.JS, even after successfully loading it into the browser

I have encountered a challenge with scaling and animating an object loaded into my web browser using WebGL. The issue arises when attempting to include animation code within the render( ) loop function, specifically with the 'object' variable whi ...

Discord between Bootstrap tabs and C3 charts: A Compatibility Str

On my website, I have implemented Bootstrap navigation tabs that each contain a chart. The issue I am facing is that when I navigate to the home page, the chart in the active tab displays perfectly fine. However, for the other tabs, the charts overlap with ...

Unable to render Javascript model in THREE JS

I am facing an issue with this code below as I can't seem to load the model. loader = new THREE.JSONLoader(true); loader.load("modelo.js" , function ( geometry, materials) { mesh = new THREE.Mesh( geometry, ...

How to assign a value to an array within a form in Angular 8

I'm facing an issue with my Angular 8 edit form that utilizes a form array. When I navigate to the page, the form array is not populated with values as expected. Can anyone help me identify and solve this problem? ngOnInit(): void { // Fetc ...

What steps should I follow to effectively store this JSONB data in PostgreSQL by utilizing node-postgres (pg)?

After receiving information in the GET URL, I need to pass it into JSON format and save it with increasing IDs into a PostgreSQL database. However, the code I wrote does not seem to be saving anything without any errors: // Initializing Pg const { Client ...

Troubleshooting: Why isn't my jQuery Click Event functioning in Mozilla but working perfectly fine in

While I know this question has been asked before, I can't seem to locate the posts I remember reading about it. I apologize for any duplication, but I am trying to implement a "click anywhere BUT here to close element overlay" effect on my personal we ...

When developing a multi-page application using React, encountering the error "TypeError: Cannot read property 'pathname' of undefined" may indicate an issue

I am facing an issue while trying to develop a multi-page application using react-router. As I am new to React, I find it difficult to explain the problem clearly. My goal is to incorporate a login page into the application. Suggestions and alternative app ...

Issue with Intel XDK: the document.location.href is directing to an incorrect page

Hello Community of Developers, I have been experimenting with different methods but still haven't found a solution. In my project using Intel XDK, whenever I attempt to change the page using location.location.href = "#EndGame" or similar codes in Java ...

Transfer the selected user content from one canvas to another

After successfully implementing a simple selection area on canvasA, I encountered an issue with copying the area to canvasB. The user is supposed to select an area and then see that selection appear on another canvas once they finish making the selection b ...

Display various React components for widgets

I am looking to display multiple instances of a widget in html. I have 3 divs with the same id, each with different attributes, and I want to render my react component three times on the page. Currently, I am only able to display the first component. Here ...

Implementing Pagination Functionality Using Knockout.js

Sample JSON Data [{ "name": "A Goofy Movie (1995) 720p HDTVRip x264 Eng Subs [Dual Audio] [Hindi DD 2.0 - English DD 2.0] Exclusive By -=!Dr.STAR!=-", "progress": 0, "size": "1.06 GB", "downloaded": "87.98 KB", "hash": "8fe65e43464debe ...

Refresh a specific div element within an HTML file when the AJAX call is successful

After uploading the image, I want it to be displayed right away. To achieve this, I am looking to refresh the div with id="imagecontainer" within the success function of my ajax call. However, I would prefer not to rely on ("$id").load("href") as it does ...

Turn off spellcheck for all material-ui elements

Is there a way to deactivate spellcheck globally for elements in the material-ui library? Before incorporating the material-ui library into my project, I used the code below to turn off spellcheck for all new DOM elements: const disableSpellCheck = funct ...

What is the best way to restrict the selection of specific days of the week on an HTML form date input using a combination of JavaScript, React, and HTML?

I need help customizing my Forms Date Input to only allow selection of Thursdays, Fridays, and Saturdays. I've searched for a solution but haven't been successful so far. Is there any JavaScript or HTML code that can help me achieve this? Below ...

Require a more efficient strategy for iterating through lines of input

One of the challenges I'm facing with my form is that it contains 5 input lines. I need to keep any blank lines that are sandwiched between two filled lines, while removing all others. For instance, if the first line is blank, the second line contains ...

Develop interactive pages in your mobile app with the help of PhoneGap

I developed a PhoneGap mobile application with a few pre-defined "html pages" (I emphasized the quotes, as they are not traditional html files). Utilizing the onsen-ui framework allowed me to consolidate all of these "html" pages into ONE index.html file. ...