Responsive div that reacts to scrolling

I am looking for a div that can dynamically change its position as I scroll up or down the page. For example, it could start 30px from the top but then move to 100px as I scroll down further.

This div will be located on the right-hand side of my page, closer to the middle. When clicking a link that causes the page to auto-scroll, the div should adjust its position to fit the new content.

Would this div need to be fixed relative to the browser window?

In essence, I want the ability to customize the top tag value of the div based on where I scroll to.

Answer №1

If you want to keep an element fixed on the page, you can define a new class called "fixed".
.fixed{ position: fixed; } After specifying the CSS styling, you can easily toggle this class using jQuery based on the user's scroll position.

Answer №2

If you want to achieve this using pure JavaScript:

HTML

<div id="floatingBox"></div>

CSS

#floatingBox {
  position: fixed;
  width: 100px;
  height: 100px;
  top: 30px;
  right: 0;
  border: 1px solid blue;
  background-color: white;
}

JavaScript

window.onload = function() {

  var body = document.getElementsByTagName('body')[0],
      floatingBox = document.getElementById('floatingBox');

  document.onscroll = function() { 
    floatingBox.style.top = 30 + Math.round(body.scrollTop / 10) + 'px';
  };

};

Check out the live demo here: http://jsbin.com/qewujuhu/2/edit

Edit:

Explanation of How it Works

Your floating box is identified by an id attribute in HTML. In CSS, its positioning is set to be fixed relative to the browser window and initial dimensions are specified. When the HTML document is fully loaded, the window.onload function is triggered. Inside this function, the <body> and <div id="floatingBox"> elements are located. A function is then defined to adjust the style attribute of the <div id="floatingBox"> element based on the scrolling behavior of the document. This updating value will change the position of the box on the page dynamically.

The expression

floatingBox.style.top = 30 + Math.round(body.scrollTop / 10) + 'px';
calculates a new value for the top property of the style object within the element found by the id. It combines the initial offset with the current vertical scroll position divided by 10 (rounded to ensure whole numbers) and appends 'px' to indicate pixels. After scrolling down, the rendered result may look like this:

<div id="floatingBox" style="top:48px"></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

Gaining a comprehensive understanding of media queries

Hello everyone, I need some help with media queries. I've been working on a website that is already responsive. However, I am required to write the code in a child theme rather than directly in the original files. When I attempt to add new media quer ...

Automatically Switch Font Colors to Red and Green

I am looking to automate the process of changing multiple textbox colors based on the class property. <input type="text" Class="ChangeColor" /> <input type="text" Class="ChangeColor" /> <input type=& ...

Import objects into THREE.js using OBJLoader, convert to Geometry, apply transformations, and finally convert to BufferGeometry

Trying to figure out why the geometry loaded with OBJLoader cannot be smoothly shaded. var loader = new THREE.OBJLoader(manager); loader.load('/manmodel/js/man.obj', function (object, materials) { console.log(object); console.log(materia ...

Function asynchronously returning Promise even after Await statement is executed

I've been attempting to develop a function that retrieves data from a document in the Firebase database using Nodejs: module.exports = async (collectionName, documentId, res) => { const collection = db.doc(`/${collectionName}/${documentId}`); t ...

Tips for clearing text inputs in ReactJS

In my current Reactjs project using nextjs, I am facing an issue with clearing input fields after a click event. Below is the code snippet that I have been working on: <form onSubmit={handleSubmit}> <input type="text" ...

Retrieve the order in which the class names are displayed within the user interface

In the following code snippet, each div element is assigned a common class name. <div id="category_9" class="list_item" data-item_ids="[38]"</div> <div id="category_2" class="list_item" data-ite ...

Clear Input Field upon Selection in JQuery Autocomplete

I've been experimenting with the Azure Maps API to add autosuggestions for addresses in an input field. https://github.com/Azure-Samples/AzureMapsCodeSamples/blob/master/AzureMapsCodeSamples/REST%20Services/Fill%20Address%20Form%20with%20Autosuggest. ...

using sass to nest multiple classes

In an attempt to utilize nested classes with Sass, I am working on a styling code that displays a button on hover. Here is the structure of my SCSS: .item{ border-bottom: 1px dotted #ccc; text-indent: 50px; height: 81%; padding: 2px; text-transf ...

Instructions on how to navigate to a class page by clicking a button in a ReactJS interface

I am currently working with React and have implemented 3 classes in separate files. The App.js file contains a navbar and button, which when clicked, displays a table from 'Table.js'. I have also added buttons in front of each row in the table th ...

How can I make a variable available on the client side by exporting it from my Node JS server built with express framework?

How can I send a variable from my Node JS server, which is built using Express, to be accessed on the client side? I need this variable to hold a value stored locally on the server and then access it in my client side JavaScript code. I discovered that ...

Having trouble retrieving the value from the input field with Angular.js

I am having trouble retrieving the value from an input field using Angular.js. Below is the code explanation. Here is my controller code: $scope.shipping=0; $scope.addProductInfoData=function(billdata){ console.log('valid',$scope.shippi ...

Is there a different alternative to @JavascriptInterface in Android WebView?

I understand how to invoke a Java method within JavaScript code using the @JavascriptInterface annotation. However, I am facing an issue when trying to determine which JS method should be called from Android. Currently, I am triggering an Android Dialog ...

Transform the date to match the user's preferred timezone abbreviation

I am currently utilizing the momentJS library for timezone conversion logic within my JavaScript code. I retrieve the User Preference Timezone abbreviation from a web service response, but when attempting to convert the date using the Timezone abbreviation ...

Acquiring JSON data within a JavaScript function using PHP

Requesting assistance on reading a JSON value using the code below, to retrieve data based on the $movieID. <script> function bookBTN(x) { <?php $url = 'http://movie.com/movieOne?seatNum=' . x; $jsonURL = file_get_ ...

The autoIncrement feature is causing a syntax error at or near "SERIAL"

Encountering a build error : Unable to start server due to the following SequelizeDatabaseError: syntax error at or near "SERIAL" This issue arises only when using the autoIncrement=true parameter for the primary key. 'use strict'; export ...

Tips for retrieving a selected date from an HTML textbox labeled as "Date"

My goal was to find the differences between two dates by utilizing an HTML Date textbox. <input type="text" name="datein" id="datein" value="" class="inputtexbox datepicker" style="display: none" is-Date/> <input type="text" name="dateto" id=" ...

stop initial focus on input field in Ionic

One issue I'm facing is that my login screen for the application automatically focuses on the 'username' input field and triggers the keyboard to pop up. This causes the contents of the login screen to push up, resulting in incorrect dimensi ...

Names changes and deletion of files that have been uploaded- Using Vue.js

I attempted to use v-model in order to rename files before uploading them to the system, but unfortunately, it was not successful. As a result, I developed an alternative solution which is functioning perfectly, except for the fact that I am unable to reta ...

Browser and contexmenu intersecting halfway

I have successfully implemented a custom context menu in my HTML project. It functions well, but I am facing an issue where half of the menu appears off-screen to the right. Is there a way to detect this and reposition the menu above the mouse pointer? He ...

Having trouble choosing multiple options from autocomplete drop-down with Selenium web-driver in Python

I am currently in the process of automating a webpage built with Angular that features an auto-complete dropdown with numerous elements. My goal is to click on each individual element and verify if it populates all the fields below accordingly. Below is th ...