Disable the 'scroll up' script for mobile devices

I am using the code below in my < head > tags to create a button that fades in when the window is 150px from the bottom.

<script>
  $(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() > ($(document).height() - 150)) {
    $("#up-btn").fadeIn(500);
} else {
    $("#up-btn").fadeOut(500);
}
});
</script>

Here is the CSS code:

#up-btn {
position: fixed;
display: none;
font-size: 1em;
font-weight: 700;
letter-spacing: 2px;
text-transform: uppercase;
bottom: -4px; right: 3%;
color: #fff;
border-radius: 2px;
background-color: #1aa97f;
padding: 18px 20px; margin: 25px auto 0 auto;
}

And here is the HTML code:

<footer>
  <a id="up-btn" href="javascript:void(0);" onclick="scrolltop();">TOP <i class="fa fa-chevron-up"></i></a>
</footer>

My goal is to make sure that the #up-btn remains hidden on mobile devices.

Answer №1

To ensure your javascript code only runs on devices with a minimum width, you can enclose it in a conditional statement like so:

if ($(window).width() > 768) {
    $(window).scroll(function () {
        if ($(window).scrollTop() + $(window).height() > ($(document).height() - 150)) {
            $("#up-btn").fadeIn(500);
        } else {
            $("#up-btn").fadeOut(500);
        }
    });
};

Simply replace '768' with the desired minimum device width for your script to execute. This snippet essentially ensures that your script will only run once the viewport size reaches an iPad-like format.

Answer №2

One way to determine if the screen size is for a mobile device in Javascript is by using matchMedia, which serves as the counterpart to CSS media queries.

For example, following the code snippet from MDN:

if (window.matchMedia("(min-width: 400px)").matches) {
  /* The viewport width is at least 400 pixels */
} else {
  /* The viewport width is less than 400 pixels */
}

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

Error encountered in React: When a parent component tries to pass data to a child

I have a Quiz object that I need to pass a single element of (questionAnswerPair) to a child component called QuestionAnswer. Although the Quiz data is fetched successfully and iterated through properly, there seems to be an issue with passing the Questio ...

Styling an Angular2 Component with a jQueryUI element

My goal is to integrate a jQueryUI range slider into an Angular2 Component. doubleRange.ts: /// <reference path="../../../../../typings/jquery/jquery.d.ts" /> /// <reference path="../../../../../typings/jqueryui/jqueryui.d.ts" /> import { Com ...

Issue with Jquery's .addClass and .removeClass functions

I'm having trouble implementing a dynamic menu on my webpage using jQuery. I've tried writing the code myself but it doesn't seem to be working as expected. The structure involves three classes: .dead, which sets display: none; in CSS, .hea ...

The functionality of the `next-auth` signOut button click does not seem to accept a variable as input, although

The Nav.jsx component code provided is working as intended. In this implementation, clicking the 'Sign Out' button will redirect the application to http://localhost:3000. 'use client' import { signOut } from 'next-auth/react&apos ...

"Troubleshooting: Why does a DT Datatable with selectInputs keep reverting back to

I recently incorporated selectize capability into the selectInputs within a column of a DT datatable in my Shiny app. Following some guidance provided here, I implemented JavaScript to enhance the style and search functionality of selectize. However, due t ...

Unable to alter the input data within the LCJS chart

I have been utilizing LightningChart JS to create scrolling line charts. After following an official tutorial by the developers on YouTube, I was able to successfully implement the automatic generated data. Now, I am looking to modify the input to a JSON f ...

The "track by" feature in Angular doesn't seem to be functioning properly when used with an array from $

Within the method of my factory, I am retrieving an array from the server using Angular's $resource: var resource = $resource("vm", { session: function() { return Auth.token(); }, all: '@all', vmId: '@vmId' ...

Retrieve the HTTP Code and Response Header for a successful AJAX request

I am attempting to retrieve the HTTP Response Code/Response Header from my AJAX request. Below is the initial script I used: $("#callContact1").click(function() { $.ajax({ url: "https://www.server.com?type=makecall", data: {}, type: ...

Is there a way for me to generate a custom subtype of Error that can be thrown?

I am attempting to create my own custom error in order to handle it differently when catching it. I want to be able to call if(instanceof DatabaseError) and execute my specific handling logic. export class DatabaseError extends Error { constructor(...a ...

ES6 does not allow the use of native setters when extending the HTMLButtonElement

Looking for a way to utilize the native setters and getters for an extended HTMLButtonElement, particularly focusing on the 'disabled' property. You can find more information about the property here: https://developer.mozilla.org/en-US/docs/Web/ ...

I am struggling to extract data from the spawned Node.js child process. What am I overlooking?

Trying to utilize a spawned command-line process for lzip in order to expand an lzipped data stream due to the lack of suitable native JavaScript tools. Succeeded in achieving this by working with files and file descriptors, although cumbersome to handle ...

Track and log specific route requests with ExpressJS morgan feature

Hello, I am currently utilizing the NodeJS web framework Expressjs along with a middleware called morgan to log requests to a file. Here is my configuration: // create a write stream (in append mode) var accessLogStream = fs.createWriteStream(__dirname + ...

"Simultaneously creating a Firebase user account and populating the database with user

My goal is to store new user information in my database using their unique user UID when they sign up through Firebase. Currently, my code is functioning properly, however, I am facing an issue where the name (which should be the created user UID) appears ...

AddThis plugin in Wordpress is unresponsive when used with a theme that relies heavily

I've been struggling to properly set up the AddThis Wordpress plugin to display share buttons below each post in an AJAX theme. After inserting this code into the custom button field on the settings page: <div class="addthis_toolbox addthis_defa ...

Safari: Contenteditable div text without spaces fails to wrap around an image when focused

In a hypothetical dialog layout, there is a div on the left side and an image on the right side. Both the div and the image start at the same vertical point. However, the text in the div is longer than the image. The desired layout is for the text to be di ...

Having trouble with the JQuery scrollTop animation? Getting the error message "Cannot read property 'top' of undefined"?

I am having trouble with my jquery animation scrollTop function. Whenever I click on <a>, it takes me to the anchor without any animation. Can someone please provide a solution for this issue? Upon running the webpage, I encountered an error message ...

Encountered a glitch during the npm installation process for mui core

I recently set up a new create-react-app and am still encountering the same error message. After installing MUI, I'm getting an 'unable to resolve dependency tree' issue. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve depende ...

Refreshing jQuery Event Bindings After Ajax Update (Using UpdatePanel)

My web page features multiple input and option elements, each with an event tied to updating specific text on the page upon any changes. I utilize jQuery for this purpose, which has proven to be incredibly helpful. In addition, I rely on Microsoft's ...

the function does not wait for the DOM content to finish loading

As I execute the code, an error occurs stating that setting innerText of Null is not allowed. I understand that this is because my function runs before the DOM is completely loaded, but I am unsure of how to resolve this issue. Attempts have been made usi ...

Emulate the impact of Stackoverflow

I'm wondering if there is a JQuery effect available to replicate the fading out of the background color when a new comment is displayed on the response wall of Stack Overflow, preferably using JQuery :) ...