Is it possible to implement specific javascript code exclusively on mobile devices?

Is there a way to restrict the execution of specific javascript code to only screen sizes below 900 pixels? My goal is to implement left and right navigation buttons for mobile devices. However, I encountered issues when trying to use matchMedia as it disrupts my code without displaying any errors. How would you suggest resolving this problem?

   var flavorScroll = (function() {

        let widthMatch = window.matchMedia("(min-width: 901px)");


    if (widthMatch.matches) {
        var flavorBox1 = document.body.querySelector('#flavor-box-1');
        var flavorBox2 = document.body.querySelector('#flavor-box-2');
        var flavorBox3 = document.body.querySelector('#flavor-box-3');
        var flavorBox4 = document.body.querySelector('#flavor-box-4');

        var buttonRight = document.body.querySelector('#flavorButtonRight');
        var buttonLeft = document.body.querySelector('#flavorButtonLeft');

        var step = 1;

        leftButton.style.visibility = 'hidden';

        function flavorDisplayer(currentStep){
            if(currentStep === 1) {
                flavorBox1.style.display = 'block';

                flavorBox2.style.display = 'none';

                leftButton.style.visibility = 'hidden';
            } else if(currentStep === 2) {
                flavorBox2.style.display = 'block';

                flavorBox1.style.display = 'none';
                flavorBox3.style.display = 'none';

                leftButton.style.visibility = 'visible'; 
            } else if(currentStep === 3) {
                flavorBox3.style.display = 'block';

                flavorBox2.style.display = 'none';
                flavorBox4.style.display = 'none';

                rightButton.style.visibility = 'visible';
            } else if(currentStep === 4) {
                flavorBox4.style.display = 'block';

                flavorBox3.style.display = 'none';

                rightButton.style.visibility = 'hidden';
            }
        }


        buttonRight.addEventListener('click', function() {
            step += 1;

            flavorDisplayer(step);
        });

        buttonLeft.addEventListener('click', function() {
            step -= 1;

            flavorDisplayer(step);
        });

    } else {

        }

})();

Answer №1

In my daily routine, I often rely on this nifty tool...

var customSize = {
  check(s) {
    const dimension = s.trim()
    const dimensions = {
      small: "480px",
      medium: "576px",
      large: "780px",
      xlarge: "992px",
      xxlarge: "1200px",
    }

    if (dimensions.hasOwnProperty(dimension)) {
      return window.matchMedia(`only screen and (min-width: ${dimensions[dimension]})`).matches
    }

    throw new ReferenceError(`The size ${dimension} is not a valid breakpoint: ${JSON.stringify(dimensions)}`)
  },
}

Simply incorporate your function within an if statement like so:

if (customSize.check("large")) {
...
}

Answer №2

Grabbing the screen.width allows you to determine the user's current screen size, which can be used to control when your code runs.

    var screenSize = screen.width;
    if (screenSize < 2000) { 
        console.log(1); 
    }

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

Protect database entries from cross-site scripting attacks

I have a project in progress where I am developing an application that extracts text from tweets, saves it to the database, and then presents it on the browser. I am currently concerned about potential security risks if the text contains PHP or HTML tags. ...

The footer is anchored at the bottom on one page but mysteriously relocates to the center on the next page

I've been working on creating a footer for my Angular application and here's the code for it: // HTML <footer class="footer"> // code for footer </footer> // LESS .footer { position: absolute; bottom: 0; width: 100% ...

Clicking on an image in a jQuery autocomplete menu will trigger a data post to an Express

My jquery autocomplete menu is functioning properly, displaying a list of books with author, title, and book image. I am now looking to enhance it by allowing users to click on the book image and then have the book title posted to an express app.post metho ...

Hovering over a container will display the text in a single line

<div class="flex-container"> <div class="red hover flex"> <h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </h1> </div> ...

Error: The integer provided in the Stripe payment form is invalid in the

I'm encountering an error that I can't seem to figure out. I believe I'm following the documentation correctly, but Stripe is not able to recognize the value. Have I overlooked something important here? https://stripe.com/docs/api/payment_i ...

The art of overriding React class methods

I am attempting to implement a class composition in react: class Entity { constructor(props) { super(props); } renderPartial() { return (<div>Entity</div>) } render() { return (<div>header {this.renderPartial()}< ...

Displaying a loading image when opening an external link using window.open

When a pop-up is opened through a window.open() function for external sites, I am looking to display a loading image icon for the links. One approach I considered is to show the loading image in a 'div' and retrieve the content of the external s ...

Unresolved Issue: Jquery Modal Fails to Activate on Subsequent Click for Ajax-

When I make an Ajax call, I load HTML into a div. This HTML content contains a jQuery modal that opens when clicked. However, on the first click, the modal opens correctly. On subsequent clicks, I receive the following error in the console: Uncaught Type ...

What is the best way to invoke the first exported function from the second exported function?

I am looking to create a file containing four or five exported functions. exports.firstFunction = function() { // some code }; exports.secondFunction = function() { // need to call firstFunction }; My issue is that I want the second expo ...

Unable to pre-fill text areas with content

Users can input data like "header" and "description_1" into a form, which is then used to create a simple one-page website for them. There is a link provided for them to edit the page, which retrieves the information stored in the database and pre-fills th ...

Upcoming: Error in syntax: Unexpected character encountered, expected a "}"

Inserted a Google Tag Manager script into a .jsx file in the following format: <!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getE ...

Tips for switching back and forth with JQuery

I have an accordion element that opens on each click, but I am wondering how to close it back again? Here is an example of the HTML structure: <ul class="accordion"> <li id="one" class="files"> <a href="#one">Calendar 1<span& ...

How is it possible to receive a TRUE value when the API returns an error message indicating that the requested photo does not exist?

I am currently in the process of learning Angular and Typescript, but I am facing some challenges. I am working on an application that involves displaying a list of photos, as well as allowing users to create, edit, and delete existing photos. However, whe ...

PHP encountered an issue while trying to compare the value stored in the $_POST variable with the value stored in a

In my current project, I have utilized a JSON file to store data and PHP to retrieve and display it. However, I am facing an issue when comparing values from $_POST - specifically, if the value contains spaces, the comparison fails. Here is the problematic ...

Tips for aligning two divs of varying sizes side by side

Imagine having two div elements: <div id="container"> <div id="left">line one</div> <div id="right">line one<br/>line two</div> </div> Is there a way to have the left and right divs align at the bottom li ...

Unable to establish connection to MongoHQ using Node.js connection URL

I have successfully set up and run a Node.js app using my local development MongoDB with the following settings and code: var MongoDB = require('mongodb').Db; var Server = require('mongodb').Server; var dbPort = 27017; v ...

Javascript code creates a blur effect on webpage bodies

On my webpage, I have multiple elements, including a "change BG" button. When this button is clicked, I want to hide all other content on the page except for the button using JavaScript. Alternatively, clicking the button could blur out all other elements ...

Adding a fresh selection to the Bootstrap menu

I'm working on a straightforward Bootstrap form that includes a select input: <div class="form-group"> <label for="category" class="control-label col-sm-3">Category</label> <div class="input-group col-xs-8"> <sele ...

Ways to incorporate dropdown menus using Bootstrap

Information regarding the inquiries ........................................................................................... <!DOCTYPE html> <html lang="en" xmlns:th="https://www.thymeleaf.org"> <head> <meta charset="UTF-8"&g ...

The json_decode function is failing to return any values, and the var_dump function is

Hey there, I know this might seem like a silly mistake to some, but I assure you it's not. I work with PHP on a daily basis and have never encountered this issue before. Recently, when attempting to convert a perfectly valid JSON document [ { ...