Is there an alternative to using CSS units of measurement when using the .css() method?

Is there a way to use .scrollTop() and .css() to adjust the margins of an element so that it floats up only when the page is scrolled, but stops at a certain margin value? I want the element to float between specific values while scrolling.

The issue I am facing is with the units. When using vh in my CSS, neither percentages nor pixels seem to work. What alternative unit or method can be used to achieve this effect?

$(document).ready(function () {

   var floater = $('#BLOCS_s1-img5');

   $(window).scroll(function(e) {
    if ( 
         ( $(document).scrollTop() > 50 && $(document).scrollTop() < 350 ) && 
         ( floater.css('margin-top') >= -35vh )
       ) { 
         floater.css('margin-top','-=2');
         }
   });

});

HTML:

<div class='BLOCS_projSample'>
    <img id='BLOCS_s1-img4' src='images/Blocs2_logo.jpg'/>
    <img id='BLOCS_s1-img5' src='images/Blocs_pp_singleMonth.jpg'/>
    <img id='BLOCS_s1-img1' src='images/Blocs_pp_hpStack.jpg'/>
    <img id='BLOCS_s1-img2' src='images/Blocs_pp_hp.jpg'/>
    <img id='BLOCS_s1-img3' src='images/Blocs1_home.jpg'/>
</div>

CSS:

#BLOCS_s1-img5 {
    width: 16vw;
    position: relative;
    margin: -17vh 0 0 30vw;
}

Answer №1

When working with jQuery, the code

floater.css('margin-top') >= -35vh
may not function as expected because

1. As mentioned earlier, using vh in jQuery is not supported, and instead you should utilize $(window).height(). This method gives you the full window height equivalent to 100vh in CSS. Therefore, to achieve a value of -35vh, you need to calculate -(35 * $( window ).height())/100, which equals -35vh.

2. The result of floater.css('margin-top') is in pixels (px), whereas our comparison value is in a unit-less format like -(35 * $( window ).height())/100. Since they have different units, they cannot be directly compared. In such cases, it's necessary to convert the value of floater.css('margin-top') into an integer using parseInt.

$(document).ready(function () {

    var floater = $('#BLOCS_s1-img5');
    var maxVH =  -(35 * $( window ).height())/100;
    floater.css('margin-top', -(17 * $( window ).height())/100);

    $(window).scroll(function(e) {

        if ( 
            ( $(document).scrollTop() > 50 && $(document).scrollTop() < 350 ) && 
            ( parseInt(floater.css('margin-top')) >= maxVH )
        ) { 
            floater.css('margin-top','-=2');
        }
    });

});
#BLOCS_s1-img5 {
    width: 16vw;
    position: relative;
    margin-left: 30vw;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class='BLOCS_projSample'>
    <img id='BLOCS_s1-img4' src='https://img.tutpad.com/tut/0/280/cover.jpg?size=548x'/>
    <img id='BLOCS_s1-img5' src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTN2AQWvohSCMmWXmoquRs6Qx8fkMP-52C8R4Izdu6Vd0mZCdfp8Q'/>
    <img id='BLOCS_s1-img1' src='https://static.vecteezy.com/system/resources/previews/000/093/616/non_2x/square-aztec-pattern-vectors.jpg'/>
    <img id='BLOCS_s1-img2' src='http://www.mygraphichunt.com/wp-content/uploads/2015/11/wpid-colorful-funky-chevron-pattern-vector.jpg'/>
    <img id='BLOCS_s1-img3' src='https://static.vecteezy.com/system/resources/previews/000/102/849/non_2x/vector-free-colorful-flat-herringbone-patterns.jpg'/>
</div>

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 smooth JQUERY fade slideshow with seamless transitions, no white gaps in

I am having trouble with the slideshow on my Wordpress website www.2eenheid.de. I want the images to fade smoothly between each other instead of fading into a white background color first and then into the next image. Can anyone help me find a solution for ...

Leveraging AJAX, PHP, and MySQL for showcasing tabular information

My goal is to dynamically display a column of data labeled as [pin], depending on the values of [plan] and [order_id]. Specifically, when plan=9 and order_id=0. I am looking to achieve this without having to reload the entire page by utilizing Ajax. Below ...

jquery event delegation doesn't function properly on statically rendered content

When trying to use jQuery event delegation, I encountered an issue where it worked perfectly on elements that were dynamically added but not on static content already present. The 'alert('test')' function performed as expected on the dy ...

managing jquery AJAX requests recursively, signaling completion to the browser

I have a situation where I need to continuously fetch data from an endpoint using a next token if there are more items available. The code snippet below illustrates how I'm currently fetching the data: function get_all_entities(campaign_id, page){ ...

Is it possible to store multiple keys in HTML local storage?

Is there a way to store multiple keys to local storage without overwriting the previous ones when multiple people take a survey and refresh? Could they be grouped by userID or sorted in any way? $('form').submit(function() { $('input, ...

Unable to align my navigation bar in the center

My navigation bar code is not centering on the website. Even after removing float: left, it doesn't move to the desired position. Can anyone help me with this issue? Thank you. css ul#list-nav { list-style: none; margin: 20px auto; paddi ...

Flashing on objects, Chrome-exclusive, utilizing background-blend-mode exclusively

Our website, www.desirio.com, utilizes a background-image on the body with the following CSS property: background-blend-mode: luminosity An issue we have noticed in Chrome is that when hovering over elements, strange white lines randomly flash on the scr ...

Add attributes to the top level

<li class="page_item"><a href="javascript:">A</a> <ul class="children"> <li class="page_item"><a href="">1</a></li> <li class="page_item"><a href="">2</a></li> </ul> < ...

Using Rails to reference an image in CSS

My application on Heroku, built with Rails, features a striking image as the background on the landing page. Since Heroku's file system is read-only, I made the decision to store these images (selected randomly) on AWS S3. In my .css(.scss) code, the ...

Issue with border spacing functionality

I'm having some difficulty with my border spacing in CSS. No matter what size I specify, it doesn't seem to have any effect. I just want to use a border for the top line. Here is my CSS: p { border-spacing: 5000px; text-align: right; ...

What is the process of nesting widgets in kendoui with the PHP wrapper?

I have created a code using treeview in manual mode. div id="treview-back"> <?php $treeview = new \Kendo\UI\TreeView('treeview'); // function to create TreeViewItem with imageUrl function ImageTreeViewItem($text) { ...

What is the best way to implement an AppBar that fades in and out when scrolling within a div?

I'm trying to implement a Scrollable AppBar that hides on scroll down and reappears when scrolling up. Check out this image for reference To achieve this functionality, I am following the guidelines provided by Material-UI documentation export defa ...

The image is failing to animate according to the PNG sequence function

Enhanced Functionality: Upon clicking the "Tap Here" image button, a function called "GameStart()" is triggered. This function ensures that the main image "Star" descends down the page from the top through an animated sequence using png logic. The propose ...

What is the most recommended jQuery version to utilize?

My goal is to change a selected button (buttons = .answerBtns) to an unselected button whenever the option in the OptionDropId drop down menu changes. Below is the jQuery code for drop down menus: $(document).ready(function () { var OptDrop = new Arr ...

Ensure that all form fields are completed and accurate before the Stripe payment modal is displayed

I've encountered an issue where the stripe payment modal appears before my form validation is complete. I am using the jQuery validation plugin for this purpose. I attempted to integrate the Stripe code within the submitHandler function, but it did no ...

Positioning the subheading "perfectly beneath the main heading" for a clean and professional look

I'm feeling a bit lost when it comes to tasks like this. While I can easily design an entire website using html and css, I start to question my approach when faced with challenges like these. Could someone offer some guidance? My goal is to have a H1 ...

Capturing errors from various pages with the Jquery Ajax .ajaxError event

Is there a way to display various Ajax request response errors in a universal dialog, similar to a standard error page? Can we capture error descriptions from multiple Ajax calls on different pages and display them using a common Ajax error event? $(doc ...

Issue with the scope causing global variable not to update when button is pressed

I am facing an issue with a declared variable and jQuery code that is supposed to store a form's value as the value of that variable when a button is clicked, and then execute a function. var verb = ""; $( "#submit" ).click(function() { verb = $(& ...

Tips on preventing right-click actions in jqGrid

While utilizing onSelectRow in a jqGrid, I have noticed that it functions properly when clicking with the left mouse button. However, when right-clicking, it still triggers the function. My aim is for the right-click to perform its usual action (such as di ...

Customizing the default font color in Angular Material

I am currently navigating through theming in Angular Material and feeling a bit disoriented. I have implemented the prebuilt indigo-pink theme by importing it into my styles.scss as shown below: @import "~@angular/material/prebuilt-themes/indigo-pink.css" ...