Back to top button displayed exclusively on desktop view (not visible on mobile devices)

I managed to create a scroll-to-top button that only appears when the user has scrolled down 25px from the top of the document. I achieved this using JavaScript by following a tutorial, as I am still unfamiliar with this programming language.

However, I would like the button to be visible only on desktop websites and not on mobile devices.

I attempted to use media queries, but they proved ineffective since JavaScript controls the visibility of the button. What function should I integrate to handle this behavior with JS?

Here is the code snippet I am currently using:

let myButton = document.getElementById("to-top-container");

window.onscroll = function() {
  scrollFunction()
};

function scrollFunction() {
  if (document.body.scrollTop > 25 || document.documentElement.scrollTop > 25) {
    myButton.style.display = "block";
  } else {
    myButton.style.display = "none";
  }
}
#to-top-container {
  position: fixed;
  bottom: 30px;
  right: 3px;
}

.to-top-button {
  background-color: #263238;
  min-height: 40px;
  min-width: 40px;
  border-radius: 20px;
  text-decoration: none;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 2px 4px 5px rgb(0 0 0 / 30%);
}

#to-top-container .lni {
  font-size: 14px;
  font-weight: 900;
  color: white;
}
<div id="to-top-container">
  <a href="#body-container" title="Back to Top" class="to-top-button">
    <i class="lni lni-chevron-up"></i>
  </a>
</div>

Answer №1

If you want to check if a media query is matched using JavaScript, you can utilize the window.matchMedia() method. You just need to specify the media query in the matchMedia() function and then evaluate the .matches property within your condition:

let myButton = document.getElementById("to-top-container");

window.onscroll = function() {
  scrollFunction()
};


function scrollFunction() {
  const matchesMediaQuery = window.matchMedia('(min-width: 600px)');
  if (matchesMediaQuery.matches && (document.body.scrollTop > 25 || document.documentElement.scrollTop > 25)) {
    myButton.style.display = "block";
  } else {
    myButton.style.display = "none";
  }
}

scrollFunction();
#to-top-container {
  position: fixed;
  bottom: 30px;
  right: 3px;
}

.to-top-button {
  background-color: #263238;
  min-height: 40px;
  min-width: 40px;
  border-radius: 20px;
  text-decoration: none;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 2px 4px 5px rgb(0 0 0 / 30%);
  /* animation: Up 2.3s infinite; */
}

#to-top-container .lni {
  font-size: 14px;
  font-weight: 900;
  color: white;
}
<div id="to-top-container">
  <a href="#body-container" title="Back to Top" class="to-top-button">
    <i class="lni lni-chevron-up"></i>
  </a>
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
... more Lorem Ipsum paragraphs ...
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

Answer №2

To prevent the display on mobile devices, you can include the following CSS code in your stylesheet. If you are using Bootstrap, be sure to add this media query:

@media only screen and (max-width: 600px) {
      #to-top-container {
        display: none;
      }
    }

Answer №3

To achieve this, you could have utilized the "a" tag instead of relying on javaScript to navigate to different pages or elements within the same page.

According to HTML specifications, using href="#top" or href="#" can direct users to the top of the current webpage.

If needed, adjust the max-width parameter in the @media query to accommodate your layout requirements.

html {
  scroll-behavior: smooth;
}
body {
  position: relative;
}
.section {
  height: 100vh;
  background: #dedede;
  margin-bottom: 20px;
  font-size: 100px;
}

.scroll-container {
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
}

.scroll-container:before {
  content: '';
  display: block;
  height: 100vh;
  pointer-events: none;
}

.scroll-container a {
  position: sticky;
  top: 88vh;
  cursor: pointer;
  font-size: 20px;
}

@media (max-width: 600px) {
  .scroll-container a {
    display: none;
  }
}
<div class="section">Section 1</div>
<div class="section">Section 2</div>
<div class="section">Section 3</div>
<div class="scroll-container">
  <a href="#top">To Top</a>
</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

What is the process for eliminating the hover effect on a Bootstrap button?

I have customized a Bootstrap button in my stylesheet to make it dark, but it still has a hover effect from Bootstrap that I want to remove. How can I get rid of this hover effect? Take a look at the code snippet below for reference: .btn-dark { min-w ...

The JavaScript function modifies the value stored in the local storage

I'm in the process of developing a website that requires updating the value of my local storage when certain JavaScript functions are executed. Currently, I have this code snippet: localStorage.setItem('colorvar', '#EBDBC2'); I&ap ...

Trigger Element Upon Click

Forgive me in advance for the lack of quality in this question, but I'll proceed anyway: All I want is for an element to slide open when clicked with a mouse! That's all! More specifically, I am looking for a single menu item that, upon clickin ...

How do you switch selection to "hold" mode using Javascript?

In my Markdown preview area, clicking on text will cause the preview area to switch to a markdown source editor automatically, with the cursor jumping to the position corresponding to where it was clicked. function onMouseDown(e) { const range = documen ...

Retrieve data from an Observable containing JSON objects

I am currently working with a Http request that returns Json data, which I then store in an observable. { "proyecto":{ "nombre": "Mercado de Ideas", "tecnologias": [ { "nombre": ".NET", "icono": "http://getsetwebsit ...

Protractor Error: Identifier Unexpectedly Not Found

I've encountered a slight issue with importing and exporting files while working on Protractor tests. HomePage.js export default class HomePage { constructor() { this.path = 'http://automationpractice.com/index.php'; this.searchQ ...

Navigate one level up or down from the current tag that contains a specified value by utilizing Scrapy

To extract the price text from within the custom-control / label / font style, I must use the data-number attribute data-number="025.00286R". This unique identifier differentiates between control section divs based on the letter at the end. <d ...

The use of the picture element, with its ability to support various image formats and sizes, must always include

Recently, I came across a VueJS template that closely resembles HTML but has the following structure: <picture> <source type="image/avif" :scrset="avif" /> <source type="image/webp" :scrset="webp" ...

Printing JSON data with multiple rows in HTML

How can I display multiple rows returned by JSON using my JavaScript function? function getScheduleDate() { //alert("enters1"); //var usrname= getParameterByName('uname'); var postVal=$.post('http://localhost/ipack/salesvisit.ph ...

Having difficulty changing the background color to black for the parent div that houses multiple child divs

Here is an example without the height attribute provided: http://jsfiddle.net/karthik64/pFcpX/ And here it is with the height attribute included: http://jsfiddle.net/karthik64/pFcpX/1/ The issue arises when I try to set a fixed 'height' attribu ...

What is the best way to incorporate an npm module in a django-admin widget without the need to install node?

Background I am working on a Django app and need to create an admin widget. The widget will display text in a unique terminal-style format to show forwarded logs from an analytics process managed by Django (using the django-twined extension). To achieve ...

How can I display an array of data with a changing name using a FlatList in React Native?

How can I render a list of array data with a dynamic name in a FlatList using React Native? Below is the list of data that I would like to display in the FlatList: const movies = [ { '4W2JJ0CLbvfLJzBUHORVaz6sAGv2': [ { name: ...

Angular component injected with stub service is returning incorrect value

While attempting to write tests for my Angular component that utilizes a service, I encountered an issue. Despite initializing my userServiceStub property isLoggedIn with true, the UserService property appears false when running the tests. I experimented ...

Using a Javascript plugin in Laravel with Vue by importing it into the project

Currently, I am in the process of creating a Vue component by utilizing the functionalities provided by the JavaScript plugin known as Cropper JS. The application is developed using Laravel 5.6. Initially, I installed Cropper JS via NPM: npm install cropp ...

JavaScript string generator for compressing CSS files into a single packaged tool

Seeking an external tool to generate JavaScript strings from a css file. The css content must be properly escaped and potentially compressed into a JavaScript string. I wish to provide my library as a single file, the JavaScript file, which may not be ac ...

Learn how to manipulate the DOM by dynamically creating elements and aligning them on the same line

Providing some context for my page: The section I have always contains a single input field. Below that, there is an "add" button which generates additional input fields. Since only one field is required on the screen, the following fields come with a "de ...

Creating new Vue components is happening towards the end of the loop

I am currently encountering an issue with my Vue components. I have structured them in a hierarchy where I have a post-index component displaying all posts, containing a post-view component for individual posts, and within that, a post-like component to ha ...

When a user clicks on a child element in ReactJS, the onclick event returns as undefined

I am experiencing an issue with my restaurants list component. While I have an onClick event set up for each list item, clicking on a child element of the list item does not trigger the expected response. When this occurs, nothing happens or I see an undef ...

What's the quickest method for duplicating an array?

What is the quickest method for duplicating an array? I wanted to create a game, but I found that Array.filter was performing too slowly, so I developed a new function: Array.prototype.removeIf = function(condition: Function): any[] { var copy: any[] ...

Can you explain the mechanics behind Angular Component CSS encapsulation?

Is it possible to avoid CSS conflicts when using multiple style sheets? Consider Style 1: .heading { color: green; } And Style 2: .heading { color: blue; } If these two styles are applied in different views and rendered on a layout as a Partial Vi ...