Looking for some help with tweaking this script - it's so close to working perfectly! The images are supposed to show up while

Hey everyone, I'm struggling with a script issue!

I currently have a gallery of images where the opacity is set to 0 in my CSS. I want these images to become visible when scrolling down (on view). In this script, I have specified that they should appear when they reach 50% of their height, but for some reason, they are appearing at 100%. Can anyone help me understand why?

<script>    

    function isVisibleInViewport(elem, percentageOfImageBeforeAppearing){
    if(typeof percentageOfImageBeforeAppearing == "undefined") 
        percentageOfImageBeforeAppearing = 0;

    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();
    var breakPoint = elemTop + (percentageOfImageBeforeAppearing/100) * $(elem).width();

    return ((elemBottom <= docViewBottom) && (breakPoint >= docViewTop));
}

function changeOpacity(){
    $("img").each(function(){
        var img = $(this);

        if (isVisibleInViewport(this, 50)){
            img.css("opacity", "1.0");
        }
    });
}

$(function(){
    changeOpacity();
    $(window).scroll(changeOpacity);
});

</script>     

Answer №1

Could you please explain why

 var break_point = elemTop + (percent_image_before_appearing/100) * $(elem).width();

uses .width() instead of .height()?

Furthermore, you are using

elemBottom <= docViewBottom

This condition checks if the element's bottom is less than the document's view bottom. Essentially asking if the image's bottom is higher than the window's bottom, meaning it is completely in view.

I believe what you actually need is

break_point <= docViewBottom

This will check if the breakpoint (the 50% point) is visible on the screen.

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

Inquiries regarding real-time alerts and notifications

Just curious, I am wondering about the creation of those notifications/alerts (for example on platforms like twitchalerts, commonly used by livestreamers). Are they typically coded in JavaScript/AJAX or another language? Is there a specific framework for ...

How can I initiate a TextChange event in ASP.NET C# without losing focus?

I attempted to trigger the TextChange event using Ajax, but it doesn't seem to be working as I expected. I'm hoping someone here can lend a hand. <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> ...

Convert the value of a Javascript variable into a PHP variable

I am feeling confused about how to pass JavaScript variables to PHP variables. Currently, I have a PHP session named example_survey and three buttons with jQuery attributes. When a button is clicked, it triggers a jQuery click event and passes the attribut ...

Exploring the power of ElasticSearch alongside Mysql

As I plan the development of my next app, I am faced with the decision between using NoSQL or a Relational Database. This app will be built using ReactJS and ExpressJS. The data structure includes relational elements like videos with tags and users who li ...

Capturing and setting form element values within a Javascript Module Pattern

I'm looking to streamline my form element access using the Module pattern. The goal is to eliminate redundancy by organizing everything under a single module. How can I achieve this without having to directly call the Anonymous function within the mo ...

What is the best way to determine if a Google Apps user is not an administrator?

We have developed an app for Google Apps and incorporated the "Integrate with Google" button [https://developers.google.com/apps-marketplace/button]. One issue we're facing is that when a user clicks on this button, they must be an administrator. Howe ...

Experience the Power of Vue.js in Your Shopify Store

I have encountered an issue while attempting to integrate 3 custom modals into Shopify. Upon implementing them, I received the following error in the console (not originating from my Vue files, but rather from the Shopify template): [Vue warn]: Error comp ...

Unable to remove spaces in string using Jquery, except when they exist between words

My goal is to eliminate all white spaces from a string while keeping the spaces between words intact. I attempted the following method, but it did not yield the desired result. Input String = IF ( @F_28º@FC_89º = " @Very strongº " , 100 , IF ( @F_28 ...

Create images from HTML pages with the help of Javascript

Hello there, UPDATE: I am looking to achieve this without relying on any third-party software. My application is a SAP product and installing additional software on every customer's system is not feasible. The situation is as follows:   ...

Is there a built-in method or library for extracting data from JSON strings in programming languages?

Duplicate Query: how to parse json in javascript The data sent back by my server is in JSON format, but it doesn't follow the usual key/value pairs structure. Here's an example of the data I'm receiving: ["Value1","Value2","Value3"] ...

Combining URLs in Angular 6 - A Step-by-Step Guide

How can I concatenate the commonUrl from CommonClass in Angular 6 for category.service.ts? common-class.ts export class CommonClass { constructor(public commonUrl : string = 'http://localhost:3000'){}; } category.service.ts import { CommonC ...

Sending data to a PHP file with JQuery Ajax: A step-by-step guide

My goal is to utilize jQuery and ajax to transmit information to a php file. However, I am facing an issue where I can only retrieve the response from ajax in json format and unable to successfully send the data. $.ajax({ url: 'myFile.php' ...

Error: A problem occurred that was not caught in the promise, please investigate further

@Injectable() class MyErrorHandler implements ErrorHandler { handleError(error) { // an error occurred in a service class method. console.log('Error in MyErrorhandler - %s', error); if(error == 'Something went wrong'){ ...

"Can someone guide me on the process of transmitting data to a client using Node in combination with

I am new to web development and struggling to understand how to transfer data from the Node server to the client while also displaying an HTML page. I am aware that res.send() is used to send data, but I'm having difficulty maintaining the client disp ...

Seeking the "onChange" functionality while implementing the "addEventListener" method

I've been busy with a React project lately. Instead of adding 'onChange' to each button within the html object like this: <input type='text' onChange={myFunction} /> I'd prefer to include it in the JS code like so: doc ...

In IE9, users can select background elements by clicking on specifically positioned links

Trying to turn an li element into a clickable link by overlaying it with an a element set to 100% height and width. While this solution works in Chrome and FF, IE9 is causing issues as other elements behind the link remain selectable, rendering the link un ...

Using the hash(#) symbol in Vue 3 for routing

Even though I am using createWebHistory, my URL still contains a hash symbol like localhost/#/projects. Am I overlooking something in my code? How can I get rid of the # symbol? router const routes: Array<RouteRecordRaw> = [ { path: " ...

Removing automatically assigned ID information in Firestore can be achieved by following these steps:

async created () { const sn = await db.collection('forms').get() sn.forEach(v => { const { title, content } = v.data() this.forms.push({ title, content, id: v.id }) console.log(v.id) }) }, del () ...

How can I add navigation dots to my slider?

I've been experimenting with my slider and I managed to make it slide automatically. However, the issue is that there is no option to manually navigate through the slides. I am looking to add navigation dots at the bottom so users can easily switch be ...

What is the best way to stop a current action when a new action is initiated?

My current setup involves an action creator that performs a costly calculation and triggers an action when the user inputs data in real-time. The challenge arises when multiple inputs are entered, as I want to avoid running the entire expensive calculati ...