adjust margin-top as user scrolls

I currently have a negative margin set on a div, but I am looking to gradually change this negative margin to 0 as the user scrolls down.

From:

margin:-150px 0 0 0;

To: (on scroll)

margin:0px 0 0 0;

I believe this effect is similar to parallax scrolling, and I came across a solution on StackOverflow: Change margin top of div based on window scroll

However, I feel like there might be a simpler way to achieve this.

$(window).scroll(function(){
if  ($(window).scrollTop() >= 1){ $('#three').css({margin:'-149px 0 0 0px'}); }
if  ($(window).scrollTop() >= 2){ $('#three').css({margin:'-148px 0 0 0px'}); }  
if  ($(window).scrollTop() >= 3){ $('#three').css({margin:'-147px 0 0 0px'}); }   
if  ($(window).scrollTop() >= 4){ $('#three').css({margin:'-146px 0 0 0px'}); }  
else { $('#three').css({margin:'-150px 0 0 0px'}); }
});

--

I have created a fiddle with the basic HTML/CSS setup for reference.

Fiddle: http://jsfiddle.net/qSe4e/

--

Thank you in advance for your help!

Answer №1

One way to streamline the generation of possibilities is by incorporating a bit of math into the process, condensing multiple lines into a single line.

For example, you can check out this demonstration: http://jsfiddle.net/qSe4e/9/

$(window).scroll(function(){
    var fromTop = $(window).scrollTop();
    $("#three").css('margin', '-' + (100 - fromTop) + 'px 0px 0px 0px');
});

Answer №2

Follow these steps

$(window).scroll(function () {
$("#element").animate({padding: "10px 20px 10px 20px"}, 2000);
});

Live Demo

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

Having trouble copying an iframe from one div to another div?

I'm having trouble transferring an iframe to another div. Here is the code I am using: <script type="text/javascript"> $(document).ready(function () { setInterval(function () { if ($('#d1').html() != $('#d ...

Creating specialized error messages for jquery's ajax() function

In my custom httphandler (.ashx) file, I have a method called Foo which throws an exception and handles it by serializing it into an AjaxError object. private void Foo() { try { throw new Exception("blah"); } catch(Exception e) ...

Selecting an option in DDSlick does not update the 'selected' attribute in the <select> element

I have implemented a jQuery plugin found at the following link: This plugin allows me to display selectable images in a dropdown select box. Everything is functioning properly, except when I attempt to load the HTML with a pre-selected option. In this cas ...

Displaying an overlay using jQuery's .fadeIn() method after switching to another browser tab

I created a script that displays numbers on a background with a fading in and out effect, similar to a matrix theme. Everything was running smoothly until I switched to a different browser tab. Upon returning to the tab with my script, the fading numbers ...

Even though the request is in the json format, Rails mistakenly interprets it as html

I've been working on setting up an API using Rails. However, when attempting to send an ajax request with json in the browser like so: $.ajax({ type: "GET", url: 'http://localhost:3000', dataType: "json", contentType: "application/j ...

To properly document the results, I must utilize a button to record the identification of a specific color

I'm working on a code that creates a clickable box which changes colors from black to green to white by going through different shades of green whenever the mouse is clicked. What I now need to do is implement a feature that displays the current shade ...

Can floating elements be disregarded by block elements?

According to W3C, the behavior of floating elements is such that: When a float is present, non-positioned block boxes that come before and after the float flow vertically as if the float doesn't exist. However, line boxes positioned next to the fl ...

Modify the drop-down value based on the selection of a checkbox in HTML

Here is the updated version that I am stuck with. <base href="http://skins4device.com"/> <link rel="stylesheet" href="/gasss/css/ghd.css" type="text/css" media="all"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.m ...

Unable to retrieve next jQuery parent element

I'm currently facing an issue I can't seem to resolve. I have a table displaying records from my database, generated through a while loop, making them all look identical. The problem arises when clicking on the delete icon, triggering a pop-up wa ...

Retrieve an item from an array using AJAX

I am working on a function using ajax that retrieves a set of values: $.each(data.dataa, function (i,item) { $.each(item, function (index, dat) { $str+=dat; }) $ulSub.append( '<li id="'+item.id +'" class="ui-widget-c ...

What steps can I take to avoid my Bootstrap Alert overlapping items in my Nav bar when displayed?

Here is the code from my _notices.html.erb file: <% flash.each do |msg_type, message| %> <div class="row pt-6 alert-messages"> <div class="col-lg-6 offset-lg-3"> <div id="inner-message" class=" ...

Avoid clicking in areas outside the perimeter of the blue circle in the SVG

Is there a way to restrict clicking outside the blue circle? The goal is to only allow opening by clicking on the svg itself, This includes everything, even white space inside the svg. How can this be achieved in the code? The current behavior is that ...

I am experiencing an issue with my css dropdown menu appearing incorrectly on both Internet Explorer and Firefox

Chrome and Safari are working perfectly fine, but I encountered an issue with IE and FF where the submenu menu appears on the left side of the main navigation. The website in question is cedumilam.php.cs.dixie.edu. Below is the CSS code I am using: # ...

Conceal a particular object from view by selecting it from the menu

I want to hide a specific element when the burger button is clicked. (See CaptureElementNoDisplay.PNG for the element to hide) When I click the burger button again to close the menu, I want the hidden item to be displayed once more. I've successfull ...

What is the purpose of setting the image border to inline block?

When I added a span element as the circular border to my image, which is placed inside a span tag, I observed that the span tag was being pushed down. By giving the span a display:inline-block property, the issue was resolved. But why does this happen? ...

The erratic appearance of inactive elements within ExtJS components

I am currently working on an ExtJS form that utilizes hbox-layout containers to generate sentences containing various form inputs. There is a specific requirement to disable the form under certain conditions. These hbox-layout containers consist of compone ...

What is the most efficient way to loop through nested JSON using jQuery in one go?

I have a substantial JSON file containing a snippet of the data shown below. The values used in the snippet are placeholders for this specific query. "restaurants":[ "name": "Burger King", "location": "Seattle, WA", "la ...

Creating colorful containers using Bootstrap

Hey there, I am interested in creating small colored boxes to represent different meanings for each color. I came across this code snippet but I am unsure how to adjust the size: <div class="p-3 mb-2 bg-primary text-white">.bg-primary</d ...

Problems with automatic resizing on Facebook while using a lightbox for fullscreen image viewing

Hey there, I'm currently working on a Facebook tab that showcases various offers. These offers are displayed using an Ari image slider along with a Joomla lightbox for full-screen viewing. I've implemented the Facebook autoresize function to elim ...

What is preventing these elements from being contained within particular divs?

I'm facing an issue with my HTML code and need some help unraveling what's happening. On my simple website, I have a container div, header div, and body div, but it seems like the HTML elements are not aligning properly within these divs (they a ...