Is it best practice to display a DIV once it is no longer visible after scrolling down?

Upon opening my website, an information box (div) appears on the screen. However, when the user scrolls down and the box is no longer visible, I want it to always appear in the top right corner while scrolling.

I have figured out how to keep it visible at all times by using position: fixed. The issue is determining when it is no longer within view while scrolling. I am open to using JavaScript for this, and I personally prefer Prototype JS.

Thank you!

Answer №1

To ensure an element remains fixed when scrolled, utilize the getBoundingClientRect() method which gives the element's position relative to the viewport. If the top position is less than 0, then it needs to be fixed in place.

Sample HTML structure:

<div id="stick">
    I should be fixed… sometimes
</div>

CSS styles:

#stick {
    position: absolute;
    top: 60px;
}

#stick.fixed {
    position: fixed;
    top: 0;
}

JavaScript code:

var stick = document.getElementById('stick');

window.onscroll = function(){
    if(stick.getBoundingClientRect().top < 0){
        stick.className = 'fixed';
    } else if(stick.className.indexOf('fixed') < 0){
        stick.className = '';
    }
}

Check out the demo here.

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

Struggling to dynamically fill the table with Ajax Json data

After retrieving data from my webservice call, I am sending this JSON response: [ [ { "id": 123, "vendorName": "PoppyCounter", "item": "Chocolate" }, { "id": 1234, "ve ...

Is it possible to slide-toggle and alter the background color of a div when clicked?

Imagine having several div's on a webpage all with the ID of "Toggle". Each div contains two other smaller divs. "Headline" which is always visible. "Comment" which appears/disappears when the headline is clicked (initially hidden). How could I ac ...

The Android WebView is unable to run JavaScript code in a local HTML file

Currently, I am attempting to load a local HTML file from the assets folder into a webview. Even though I can successfully load the HTML file in the webview, there seems to be an issue with the file's reliance on an external .js file for calculations. ...

Troubles arise with IE8 when using Position: fixed styling

Here is the CSS code I am using: background-color: White; border: 2px solid black; padding: 10px; position: fixed; right: 5px; top: 0; width: 250px; While this code works well in Chrome, Firefox, and Safari, I am facing issues with IE8. The position of t ...

Floating dropdown within a scrolling box

How can I ensure that the absolute positioned dropdown remains on top of the scrollable container and moves along with its relative parent when scrolling? Currently, the dropdown is displayed within the scrollable area. The desired layout is illustrated i ...

Having difficulty with my async custom react hooks. Is there a way to wait for the result of one hook before using it in another hook?

Having some difficulty working with custom react hooks. I've created 2 custom hooks - one for fetching an ID and another for fetching a profile using the previously fetched ID. Since the second hook is dependent on the ID, I need to await the promise ...

Issue with toggleClass not functioning properly after receiving data from an AJAX call

On my website, I have a link that triggers an AJAX request. However, when the response comes back and I try to use the toggleClass function in the following .js code snippet, it doesn't work as expected: $(document).ready(function(){ $("td").click( ...

An error was encountered stating "TypeError: Unable to call function on undefined object while attempting to utilize a JSON object

My current setup involves using D3js with MongoDB and AngularJS to showcase my data. Everything works smoothly until I decide to give my JSON array a name. Suddenly, Angular starts throwing errors at me and I'm left confused as to why. Here is the or ...

The execution of the function halts as soon as the player emerges victorious

In my attempt to create a basic game where players compete to click their designated button faster to reach 100%, I am in need of assistance with implementing a logic that determines the winner once one player reaches or exceeds 100. Essentially, I want ...

Venom Bot encounters issue with sending files, displaying "Error processing files" message

When attempting to send a PDF in the code snippet below, I encountered the following error: app.post('/send-pdf',[ body('number').notEmpty(), ], async (req, res) => { const errors = validationResult(req).formatWith(({ msg }) =&g ...

Using Ajax, transmit an array from javascript to a php function

How can I send an array from JavaScript to PHP using AJAX? I'm not sure how to do this, especially when trying to send it to a PHP function like a controller class. Can someone please correct me if I'm wrong? Below is my current JavaScript code f ...

The React Context Value keeps coming back as undefined every time

As a beginner working with contexts, I am taking it slow. Recently, I came across logging Providers to test the value and encountered a constant 'undefined' result. To troubleshoot, I tried moving them side by side in the code to see if it makes ...

AngularJS routing with html5mode causing 404 error when using htaccess

I am currently working on my very first angularjs application using version 1.6x, and I am encountering some 404 errors with my router. Here is how my router is set up: app.config(function($routeProvider, $locationProvider) { $locationProvider.html5M ...

Trouble Displaying DHtmlX Scheduler Events on Safari and Internet Explorer

I have recently embarked on the journey of building a nodejs application and decided to incorporate DHtmlX Scheduler as my calendar. To my dismay, I encountered an issue where the events are not displaying on Safari or IE, despite working perfectly fine on ...

Carousel with Bootstrap: Heading positioned over the content

My goal is to have the caption of Bootstrap Carousel displayed above the content, but I'm encountering issues with it. When clicking on the chevrons, you may notice the < Item 1 > bouncing... (This behavior is a bug, and logically speaking, I ex ...

Is there a problem with textbox support for multi-line strings?

I'm having trouble getting a textbox to display multiple lines of text. For instance, when I copy three lines of text from Microsoft Word and paste it into the textbox, only the first line appears. The other two lines are not showing up, and I'm ...

Angular15: How can we properly provide support for legacy browsers?

I'm having issues with my Angular build on IOS12 as it's only displaying a blank page. Below are the dependencies listed in my package.json: "dependencies": { "@angular/animations": "^15.0.0", "@angular ...

What is the most efficient way to transfer a string to a python program using ajax and retrieve a string in return?

I'm experiencing a problem with my ajax request where I am sending an object to a python program using JSON: $.ajax({ url: "http://localhost/cgi-bin/python.cgi", type: "POST", data: JSON.stringify(myobject), dataType: ...

How to extract data from Google Sheets using NODEJS?

When utilizing the REST API to extract data from a cell range in Google Sheets, the response returned is as follows: { "range": "RECORD!A2:J2", "majorDimension": "ROWS", "values": [ [ "07/11/2016", "21:20:10", "3", "MAIN" ...

Issue with highcharts and vue.js: creating a unique chart for displaying measurements

Currently, I am integrating Highcharts and Vue.js simultaneously while incorporating multiple charts on my webpage. As of now, I have successfully displayed data on all the charts without encountering any issues. However, my goal is to assign a special tit ...