Learn how to swap out the traditional "back to top" button with a customized image and make it slide onto or off the page instead of simply fading in and out

As a newcomer, I am trying to replicate a unique "back to top" effect that caught my eye on another website. Instead of the traditional fade-in approach when scrolling down, the "back to top" image in question elegantly slides out from the bottom right corner of the screen. Moreover, I would like to swap out the current button with an image, but sadly my HTML skills are letting me down in this regard. Any assistance offered will be highly appreciated.

<a href="javascript:void(0);" id="scroll" title="Scroll to Top" <img src="images/logo_bluebird_90_cc.png" style="display: none;">Top<span></span></a>
#scroll {
  position:fixed;
  right:10px;
  bottom:10px;
  cursor:pointer;
  width:50px;
  height:50px;
  background-color:#3498db;
  text-indent:-9999px;
  display:none;
  -webkit-border-radius:5px;
  -moz-border-radius:5px;
  border-radius:5px;
}
#scroll span {
  position:absolute;
  top:50%;
  left:50%;
  margin-left:-8px;
  margin-top:-12px;
  height:0;
  width:0;
  border:8px solid transparent;
  border-bottom-color:#ffffff
}
#scroll:hover {
  background-color:#e74c3c;
  opacity:1;
  filter:"alpha(opacity=100)";
  -ms-filter:"alpha(opacity=100)";
}
$(document).ready(function(){
    $(window).scroll(function(){
        if($(this).scrollTop() > 300){
            $('#scroll').fadeIn();
        }else{
            $('#scroll').fadeOut();
        }
    });
    $('#scroll').click(function(){
        $("html, body").animate({ scrollTop: 0 }, 600);
        return false;
    });
});

Answer №1

Your setup has a few mistakes, particularly in how you coded the anchor. In reality, an anchor tag is not necessary since you are already using jQuery to adjust the position on click. I have streamlined your code by removing any unnecessary elements. Here's a simplified version of what you're trying to achieve:

$(document).ready(function(){
    $(window).scroll(function(){
        if($(this).scrollTop() > 300){
            $('#scroll').css("right","10px");
        }else{
            $('#scroll').css("right","-140px");
        }
    });
    $('#scroll').click(function(){
        $("html, body").animate({ scrollTop: 0 }, 600);
        return false;
    });
});
section {
  height:1200px;
}
#scroll {
  position:fixed;
  right:-140px;
  bottom:10px;
  width:100px;
  height:100px;
  opacity:.7;
  -webkit-transition:all .4s ease;
  -moz-transition:all .4s ease;
  -ms-transition:all .4s ease;
  -o-transition:all .4s ease;
  transition:all .4s ease;
}
#scroll:hover {
  opacity:1;
  cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<section>
    <img id="scroll" src="https://via.placeholder.com/150">
</section>

In essence, the image is hidden off-screen with a fixed position of right:-140px. The jQuery script adjusts this position to right:10px when the specified scroll distance is reached, and returns it back when above that point. Since the jQuery handles the scrolling function, an a tag is not needed here. The section element is added for demonstration purposes to provide scrolling height on the page.

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 there any advantage to placing buttons within an HTML form?

What benefits are there to placing a button within an HTML form as opposed to directly in the body? <form id="viewForm" method="post"> <input id="editBtn" type="button" value="Edit" /> </form> ...

Issue encountered with Fabric js: Unable to apply pattern fill to a group of rectangles

Greetings, I am in need of some assistance with a coding issue. I have a for loop that generates and adds multiple rectangles to a fabric js canvas. To set a texture for each rectangle, I am using the following code snippet. var rect = new fabric.Rect( ...

php receiving the selected value from a dropdown list in the action

I am aiming to retrieve two drop-down values and then 1. pass them to the `action` function and 2. send them to the next `.php` page using `$_POST`. Essentially, I want to choose the php `action` with a drop-down menu. Where am I going wrong? When I selec ...

While working with ajax form submission in CodeIgniter, I encountered an issue where I did not receive the expected value in the

For my project, I am using PHP Codeigniter and submitting a form through an Ajax call. However, I am facing an issue where I am not receiving the expected value in the success message. Below is the code snippet: Ajax Call: function addLocation(){ va ...

Merging two arrays with lodash for a seamless union

Here are two arrays I'm working with: arr1 = [ { "key1": "Value1" }, { "key2": "Value2" }, { "key3": "Test3" }, { ...

The showdown: JQUERY $(document).click versus $(document).ready

$(document).ready(function(e) { if ($('#sidebar').hasClass('active')) { $('#dismiss, .overlay').on('click', function() { $('#sidebar').removeClass('active'); $('.overlay&apo ...

Avoiding the reset of a variable when utilizing state in React

Is it possible to have a variable in React that remains unchanged during rendering without using context or moving it up the components hierarchy? import React, {useState,useMemo,useRef} from 'react' const Component=()=>{ const [state,setS ...

Configuring JSON in PHP and JavaScript

Although I have already asked this question before, I am experiencing some issues in my code. I know that utilizing JSON is necessary and after researching multiple sources, I grasp the concept but somehow am unable to implement it correctly. Here is my co ...

Can you modify the current HTML code of a Wix website?

I am currently developing a website using Wix and have encountered an issue with the page description. Despite editing it in Wix, the changes are not reflecting on the live site. Upon inspecting the source code in Chrome, I identified the problem lies wi ...

Tips on setting pre-defined data in a ReactJS form builder field

Currently, I am utilizing the reactjs-form-builder to create forms within a React.js environment. Below is an excerpt of my fields object: this.state = { id: null, loading: true, fields: { "fields&qu ...

Is the concept of WebSockets simply adding unnecessary complexity?

Let me know if I'm mistaken... The implementation of firewalls was initially meant to limit internet access for Corporate employees (and indirectly safeguard home users). Now, with the introduction of WebSockets, applications are able to tunnel any ...

The JavaScript function is returning a value of undefined

I encountered an issue where my Javascript function is returning undefined even though it alerts the correct value within the function itself. I have a setup where I call the function in my 1st controller like this: CustomerService.setName(data.name); A ...

Removing single quotes and replacing them with spaces when passing data from JavaScript to MySQL

I'm currently focused on JavaScript using Hapi.js in my role at the company. My main task involves retrieving data from MongoDB and transferring it to a MySQL database. The challenge arises when dealing with data that contains single quotes within th ...

How can you efficiently load the materials for a THREE.BoxGeometry using THREE.LoadingManager()?

I am looking to enhance the image quality of a geometry after user interaction by initially loading low-resolution assets and then switching to high-resolution assets when the user interacts with it. When using the following standard code: var materials = ...

Adjust the size of a div element dynamically to maintain the aspect ratio of a background image while keeping the

Utilizing the slick slider from http://kenwheeler.github.io/slick/ to display images of varying sizes, including both portrait and landscape pictures. These images are displayed as background-image properties of the div. By default, the slider has a fixed ...

Transmit information using $broadcast when a button is clicked, and retrieve that information using $scope.$on

I am trying to create a function that will broadcast data from the server upon button click, and then navigate to a new route using $state.go('new-route'). In the controller of this new state, I want to retrieve the transmitted data. However, whe ...

Unexpected results occur when accessing data in $uibModal.open() within Angular JS causing it to

Here is the code snippet that is causing the issue of returning undefined items in AngularJS: App.js code console.log('single page application script is working'); var myApp = angular.module("demoApp", ["ngRoute", 'ui.bootstrap',&apos ...

Choose the child nodes upon selecting the root node

I am trying to implement a 2-level material-ui treeview where selecting the root node should automatically select all child nodes as well. Does anyone have suggestions on how to achieve this with material-ui treeview? For more information, please visit ma ...

Sending a php DateTime object to javascript using Ajax

I sent a php datetime object via ajax. Now, I am able to access it in javascript like this: {"timezone":{"name":"Asia\/Tokyo","location":{"country_code":"JP","latitude":35.65231,"longitude":139.74232,"comments":""}},"offset":32400,"timestamp":147265 ...

Create a connection between two draggable boxes by drawing a line with Selenium WebDriver using Java programming

My current project involves working with Selenium Web Driver, however, my application does not support CSS selectors. Within the application, there is a Flowchart page where I am tasked with adding a FlowChart. This requires dragging and dropping two recta ...