Utilize JQuery addClass to implement CSS animations that run only once by setting a boolean variable to true or

I am working on a CSS animation that I want to trigger when the page is visible in the browser. To achieve this, I am using a function that determines the position (referred to as "posish"). The animation should run once when the page comes into view or when posish is true (13900), and once again when posish becomes false.

However, my issue arises when both true and false conditions trigger the animation continuously while scrolling. I want the animation to only run once for each condition change before switching to the opposite state. Additionally, I have two classes applying the same animation, allowing me to add and remove them accordingly. I hope this explanation clarifies the situation! Below is the code snippet:

if (posish(13900)) {    
    $('.shadow').removeClass('shrink-2');   
    $('.shadow').addClass('shrink-1');
} else {
    $('.shadow').removeClass('shrink-1');
    $('.shadow').addClass('shrink-2');  
}

Here is the code for the posish function

function posish(pos) {
    pos-=19;
    if (scrolled-viewport/4 < pos) {
        return false;
    } else if (scrolled > pos+viewport/2) {
        return true;
    } else {
        return (scrolled-viewport/4-pos)/(viewport/4);
    }
}

If you require any additional information, please let me know. Thank you for any assistance!

Answer №1

Sure thing! Here's a Fiddle I created to showcase some code:

http://jsfiddle.net/3XbTG/

If you run it and check the console, you'll see that it accurately tests the two position values.

It seems like what you're aiming for is to determine if the "pos" value is greater than one quarter of the total viewport height (height + scroll position - 19).

The first issue lies in obtaining the current values of viewport and scrolled every time the function is executed.

The second problem is that you should only perform a single test and return the result directly. Your function was returning either booleans or numbers, leading to confusion.

function posish(pos) {
    var viewport = $(window).height();
    var scrolled = $('body').scrollTop();
    var totalHeight = scrolled + viewport - 19;
    return (totalHeight / 4 < pos);
}

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

Creating a semi-transparent div using CSS

My new project involves a background image with a div overlay. I'm hoping to make this overlay partially transparent so that the underlying background is still visible with some opacity. As someone who is just starting out with CSS, any guidance on ac ...

Tips for creating a plug-in plugin and applying the necessary parameters

(function( $ ){ var functions = { init : function( options ) { var settings = $.extend({ //Declaring default settings that can be overridden in the plugin call code: 7, listHe ...

Add a decorative frame around the heading and text block

I'm looking to encase both the header and paragraph in a single border. Right now, they each have their own separate borders. How can I combine them into one? <style type="text/css> h1, p { font-family: consolas; border: 2px solid #73AD21; bor ...

Clicking two times changes the background

I am facing an issue with three boxes on my website. Each box is associated with a corresponding div. When I click on any box, the div displays and the background color turns red. However, when I click on the same box again, the div disappears but the back ...

Optimizing performance with queues and asynchronous requests in jQuery

Having two functions and facing a single issue. hideTable(); ajaxCall(params); The hideTable function is defined as follows: function hideTable() { if (effects) { $('#jquerytable tbody').fadeOut(speed); } } I am looking to ha ...

Tips for accessing and displaying JSON data using jQuery

Data in JSON format: [ { "ID":"25", "Serial":"1", "Purchase_id":"8", "Item":"23", "Unit":"1", "HSN":"84212120", "Quantity":"10", "Purchase_rate":"100", ...

Stop Duplicate Error Messages with jQuery Validation Plugin

I have a specific rule in place that requires the total quantity selected for each Stage to match the number of passengers listed on a booking. Each Stage is outlined within a DIV, as shown in this example:- HTML <div id="Stage_1"> <select d ...

Secure your jQuery/AJAX request by encrypting it before submitting

My jquery Ajax method is triggered by a button click event. This method calls the controller and passes parameters to retrieve data from the database. Upon clicking the button, the following URL appears in the console of the developer tool bar: http://lo ...

Looking for assistance with automated web testing using selenium

I am currently using Selenium to carry out testing on a web application, but I have encountered an issue. One of the nodes that needs to be clicked has a value that constantly changes upon startup. For example: click css=#f0012 > ins.jstree-icon At s ...

Bootstrap 4's mobile flexbox expends beyond the desired width

I'm facing an issue with my code snippet: <div class="row"> <div class="w-100 col-auto col-lg-5 w-auto p-3 p-lg-5 m-4 rounded-sm bg-dark text-white shadow-lg"> <h3>This is a very very very long Text</h3> </ ...

Create a triangular shaped division element to contain text and automatically close when the user moves the cursor away

Is there a way to create a triangular div that can display text and images? I tried this method, but the issue I'm facing is that when the div opens on hover, it doesn't close properly when I hover out. Since the div is in a square shape, how ca ...

Issue with AngularJS directive template not rendering on the webpage

I have created an AngularJs directive that is supposed to display a div in the template. However, when I run the code, nothing appears on the screen. Below is the HTML code: <div ng-app="SuperHero"> <SuperMan></SuperMan> </div> ...

Only parameters will be passed to the MVC controller if Ajax is initiated and an alert is triggered

I've encountered a peculiar situation. I have two ajax POST requests. Initially, I faced issues with passing parameters to the controller, but eventually managed to get them through. However, I noticed that all values are only received in the controll ...

How does the PhoneGap API handle Timestamp format?

Within the realm of app development, phoneGap offers two vital APIs: Geo-location and Accelerometer. Both these APIs provide a timestamp in their onSuccess method. In Accelerometer, the timestamp appears as '1386115200', whereas in Geo-location i ...

Why does my text keep aligning to the left when I adjust the width, causing my background to remain attached to the text?

When I add a width attribute to my #information h1 id, it seems to override the text-align: center; property and aligns the text/background to the left instead of center. Basically, I need assistance in centering the headers with the appropriate backgroun ...

Issue with unrecognized expression in JQuery when processing Ajax response

Recently, I implemented a JQuery Ajax Form on my website. $('#modal-body-sign-in').on('submit', '#sign-in', function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr(&apo ...

Ionic 4: Facing issues with setting complete background image on ion-card

https://i.stack.imgur.com/3lH6h.png I'm currently attempting to set a background image for an Ion-card in order to completely cover the card's area. However, I'm facing an issue where the background image does not cover the entire area and ...

Using a PHP post request in AJAX via jQuery to fetch JSON formatted results, enabling the addition of closed Google Map markers

Currently working on a small project involving Google Maps. The goal is to retrieve coordinates from a database using Ajax and update the map without refreshing the page. PHP Code: $deviceID = $_POST['deviceID']; $sqlLocation = "SELECT * FROM ...

Adjust fancybox height using jQuery

I am working on a project where I need to display a fancybox containing an iframe from another domain. The iframe has dynamic content and its height may change based on the pages it navigates to or the content it displays. I have access to the code of the ...

Animating divs one by one using CSS3 with delays

I am experimenting with animating three separate divs one by one, each moving down 50px as a test. Here is the SCSS code I am using: .action { margin: 20px 0; text-align: center; transform: translate(0,0); transition: ...