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

I am having trouble getting Stripe Elements to function properly within Laravel

I'm currently developing a subscription app using Laravel and trying to integrate Stripe Elements, but I'm encountering issues with getting it to function properly. Below is my form: <form method="POST" action="/subscribe" id="payment-form"& ...

Encountering an issue of receiving an undefined response while attempting to retrieve JSON data from a

I'm trying to access JSON data from this specific URL: here However, I keep receiving an undefined value when attempting to retrieve it. Strangely, I can view the JSON data in the response using developer tools, but for some reason, I am unable to p ...

Retrieve the user information from Auth0 within the NestJS application

I am currently working on implementing Auth0 authorization in NestJS, but I am unsure of how to retrieve the user's data within the callback URL handler. In a normal express function, this issue could be resolved using the following code. The passpor ...

What is the purpose of enclosing an Angular app within a function?

As I delve into learning Angular, I've encountered a recurring snippet in the app.js file across various resources: (function () { \\\myAngularModules })(); Despite its prevalence, the explanation provided is often just ...

What are some methods for utilizing the data received through this.props.history?

Whenever I need to navigate from one route to another using this.props.history.push("/"), I also want to pass along some extra data. For example: this.props.history.push('/postDetail', {data: item}). However, I am uncertain about where to define ...

What is the best way to define Bootstrap 5's CSS variables with the :root selector?

I am working with a Bootstrap 5 application that utilizes various web components, all styled with Bootstrap 5. I am looking to dynamically customize the theme within the parent component that integrates these web components. The basic structure of my setup ...

The display of options in React Bootstrap typeahead is not functioning properly

When I try to implement React Bootstrap Typeahead, the options do not appear in the Typeahead component upon page load. Here is a snippet of my code: const React = require('react'); ... (code continues) The options are generated as follows: [ ...

What strategies can I use to streamline this array update function code?

Looking to simplify my updated array function. The update function involves updating and comparing values in an array. The comparison will be done within the fruit_temp. For example, data in fruit_temp's fruit_db_id corresponds to an existing id in th ...

The function is not triggered when the select tag is changed

I'm currently working on implementing a drop-down menu using the <select> element in HTML. Here is the code snippet I have so far: <select id="Parameter1" onchange="function1()"> <option value = "0105" name = "Frequency">Frequency ...

React - the constructor binding issue with 'this' keyword

I am a beginner in React and I am learning through creating a simple test application. However, I am facing an issue with "this" binding. I set up this app package yesterday using "create-react-app", so all the necessary plugins including babel should be u ...

Fast JSON retrieval

I am attempting to implement an instant search feature using json. Despite my efforts, the code does not seem to be functioning properly. Can someone kindly review it and assist me in resolving the issue? Thank you in advance. http://jsfiddle.net/hMyr7/ ...

The Route.get() function in Node.js is expecting a callback function, but instead received an unexpected object of type

Recently, I started coding with nodejs and express. In my file test.js located in the routes folder, I have written the following code: const express = require('express'); const router = new express.Router(); router.get('/test', (req ...

Windows Outlook - automatic tag wrapping feature

My goal is to ensure that buttons wrap properly inside their cell. I have set a max-width for the cell as well as a ghost table of 200px. The width should not extend past 200px, causing the span to wrap to the second row automatically. This method works ev ...

What is the best way to dynamically change the content of a div based on user selection?

When a user selects an option in the HTML, I want to display another div set to Block. I tried putting the OpenAskuser() function in a button, but it didn't work either. It would be ideal if we could achieve this without a button. Just have the displ ...

Just starting out with CSS and coding. Setting up radio buttons and divs for a simple beginner's gallery

One challenge that perplexes me is how to reposition the concealed divs below the radio buttons with labels. Check out my HTML here View my CSS code here /*color palette: abls [lightest to darkest] #eeeeee #eaffc4 #b6c399 ...

typescript throwing an unexpected import/export token error

I'm currently exploring TypeScript for the first time and I find myself puzzled by the import/export mechanisms that differ from what I'm used to with ES6. Here is an interface I'm attempting to export in a file named transformedRowInterfac ...

Locate a specific class inside a div and switch the CSS style to hide one element and reveal another

I have two divs, each containing a span. By default, the display of each span class is set to none. My goal is to toggle the display property of the span within the clicked div. If the span is already visible, I want to hide it; if it's hidden, I want ...

backbone.js router failing to recognize URL fragments

I have set up a basic router in my code and initialized it. Issue: I encountered an unexpected behavior when visiting the URL http://localhost/backbone1/#photos/5. Despite expecting an output from console.log() in the JavaScript console, nothing appears. ...

Count the amount of exposed items in each row within a specific container size and dimensions

I created a code sample available at demo code to showcase li elements within a ul displayed in a flow-like manner with the use of display:inline. The challenge I am facing is determining the number of complete li items that are not wrapping for each row ...

Tips for splitting the json_encode output in Javascript

Looking for help with extracting specific values from JSON data retrieved via PHP and AJAX. I only want to display the agent name in my ID, not the entire object that includes "name" : "Testing". Here is the console output: [{"agent_module_id":"1","agen ...