Tips for designing a sleek and seamless floating button

I attempted to implement a floating button feature that remains in view while smoothly flowing using jQuery. I followed a tutorial I found online to create this for my website. The tutorial can be accessed at this link. However, after following all the steps outlined in the tutorial, it seems that something went wrong as the functionality is not working as intended.

Below is the code snippet:

$().ready(function() {
    var $scrollingDiv = $(".floatBtn");

    $(window).scroll(function(){            
        $scrollingDiv
            .stop()
            .animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );          
    });
});
.floatBtn{
position: absolute;
float: right;
right: 0;
text-align: right;
z-index: 5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<p>
Lorem ipsum dolor sit amet, an has dicat aperiri delicata, te maiorum omittantur theophrastus vim, ut quot sapientem reprehendunt eam. Exerci omnium eu eum, legendos explicari sed ad. Apeirian mandamus vix et. Tollit dolorem has at, mod...lorem labore consequuntur sea, ne debet sententiae constituam pri.

Utamur adipisci sadipscing has ex. Tantas voluptatibus ius ei, vel definiebas signiferumque at. Lorem voluptaria te vel, cum ne consequuntur necessitatibus. Ex suas probo propriae cum. Duo ullum abhorreant dissentiet no. Fuisset consequat vim no.
...
Atqui invenire vim in, no usu possim tractatos principes. Invidunt probatus est te, eos ea error sententiae, id alterum nostrum sea. Mollis moderatius omittantur has ex, falli movet te has. At viris commodo deserunt quo.

Eu tale putent referrentur vix, cu quo admodum voluptatum appellantur. Usu ne ignota prodesset, ipsum quando an eos, dolores abhorreant an quo. Cu assum consequat ius, lobortis consequat eos no, ne mea suas congue viderer. Semper latine eripuit in quo. Vel...

In the scroll function, when scrolling down, the floating button also scrolls further down instead of staying within the viewing area, which is not the desired behavior. Any help or suggestions would be greatly appreciated. Thank you in advance!

Answer №1

To ensure a button remains visible at all times, it is important to use the position fixed property. By positioning the element relative to the viewport, the button will be constantly visible on the screen. Here's an example of how you can achieve this without using jquery:

.floatBtn{
   display: block;
   position: fixed;
   width: 200px;
   height:200px;
   color: red;
   border: 3px solid black;
   top: 20px;
 }

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

Is your Javascript navigation functioning properly on some submenus while encountering issues on others?

If you visit , you'll notice that it's a visually appealing site. The navigation submenus seem to be functioning properly, HOWEVER upon inspecting the element, you'll notice that under the PRICING tab, there are submenus that have the same c ...

I am encountering the error 'user.matchPassword is not a function' while making a call to my API using bcryptjs in my Node.js and Express application. Can someone help me understand why

const checkUserAuth = asyncHandler( async (req,res)=>{ const { email , password } = req.body; const foundUser = User.findOne({email}); if(foundUser && (await foundUser.verifyPassword(password))){ generate ...

Executing a Component function within an "inline-template" in VueJS

VueJS version 1.9.0 app.js require('./bootstrap'); window.Vue = require('vue'); Vue.component('mapbox', require('./components/mapbox.js')); const app = new Vue({ el: '#app' }); components/mapbox.js ...

How can you modify the color of a card in React by mapping through an array and evaluating its value?

I'm attempting to modify the color of a card depending on the current slot value, which is an object in an array. While I am iterating through each card, I want to adjust the background color of the card based on this value. However, my current method ...

Making an Ajax request with JSON is yielding unexpected variables that cannot be modified or removed

Attempting to make an AJAX call using a script: $.ajax({ url: pageURL, data: loadData, type: 'POST', cache: false, dataType: 'json', success: function (data) { //if the call was successful console.log(su ...

Determine the total number of days using the bootstrap date range picker

Currently, I am utilizing the bootstrap jquery daterangepicker in order to determine the number of days between 2 dates. Within my HTML code, I have implemented 2 input fields as shown below: <div class="col-12 form-group has-feedback"> <labe ...

Masonry grid showcasing a diverse image gallery with varying widths and heights

I have created a gallery layout for my website where I want to display images in a grid style that is both responsive and has random width and height. However, all the images I have are vertical, which creates a challenge for me. Any assistance on how to t ...

Stop SVG Text from Rotating using CSS

I designed an SVG circle containing text and now I would like to apply a CSS transform to rotate the SVG, but without rotating the text element. .progress { webkit-transform: rotate(-90deg); transform: rotate(-90deg); } .progress__value { stroke-d ...

Optimizing Angular's ng-repeat for efficient updates by restricting the watch functionality to the relevant iteration

My task involves creating a table where users can edit certain fields in each row, which will impact other fields within the same row. Due to this requirement, I cannot use bind-once for all the rendered data. To address this issue, I attempted using the ...

Can Mongoose be integrated into a Next.js API environment?

My current project involves creating a website for my sister to showcase and sell her artwork. Utilizing Next.js, I have set up the framework where the website displays the artwork by fetching an array from a database and iterating through it. Let's ...

Reverse changes made to a massive object and then redo them

My current project requires the implementation of undo-redo functionality for a product. At the moment, I am managing a substantial Object retrieved from a MongoDB collection The structure is as follows: { cart:{ products:[ { name: " ...

Issues with jQuery tabs "load" function not functioning properly

I created a function that triggers an ajax request onClick and generates a new tab with the loaded data. While it works well, I want to enhance the user experience by loading the tab after the function is complete, eliminating the need for the user to clic ...

Can pure Javascript be used to integrate Bootstrap pagination into a Bootstrap table?

I have created a custom JavaScript code to generate a Bootstrap table with hardcoded values. Now, I am looking to implement Bootstrap pagination using JavaScript only. var table = document.createElement("table"); table.className = "table"; var the ...

Challenges with aligning Fontawesome stacks

I utilized the code example from Fontawesome's website to create a pair of stacked social media buttons and enclosed it in a div element to float them to the right side of the page. <div class="social-icons"> <span class="fa-stack fa-lg"> ...

Issue with exporting to Excel in AngularJS in Internet Explorer not functioning as expected

Having some trouble exporting data to Excel or PDF in IE, but it works fine in Chrome. Since most users will be using Internet Explorer, can someone please review my code and provide suggestions? Below is the Angular function I am using: scope. ...

Tips for accessing a website and logging in to extract important data for scraping purposes

Currently facing an issue with scraping data from a website that requires logging in. I've been attempting to use the node request package for the login process, but so far have been unsuccessful. The code snippet I'm currently using is: var j = ...

Using a PHP if statement within a for loop to add the output to individual divs

Despite relying on stackoverflow for answers in the past, this is my first time posting a question here. I have extensively researched my issue but couldn't find a solution. Hopefully, providing the actual question will help. So here's the situa ...

What is the best method for applying a style specifically to controls located on the lower part of the

I am currently working on designing a table in a webpage and need to set styles for the <td> tags. Is it possible to apply different styles to the upper and lower cells? Can I use a <style> that specifically targets the bottom <td> tags? ...

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 ...

How can I clear my object so that new Dates() can be added to my calendar?

I am working on updating my program to seamlessly replace old JSON data from a holidays API with new data as soon as it is received. Initially, I attempted to declare the array as empty at the start, but this approach did not yield the desired results. Si ...