Include specific javascript files only for smartphones

Recently, I encountered an issue with a JavaScript code that swaps background images on scroll down. To address the problem with debounce, I ended up setting different debounce times for various browsers (I am aware this is not the ideal solution, but it's getting the job done for now as I am still new to JavaScript).

However, another hurdle emerged when scrolling on my phone - it was happening too quickly. In an attempt to resolve this, I tried setting a different debounce time for screens smaller than 480px, but unfortunately, it didn't work as expected. It seems like the "browser if" condition is overriding the "width if" condition, and I'm uncertain about how to rectify this.

Below is the current code snippet (admittedly, it's not the cleanest due to my novice status in JavaScript):

$(document).ready(function(){


    var isFirefox = typeof InstallTrigger !== 'undefined';  
    var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    var isChrome = !!window.chrome && !isOpera;   

    var numberofscroll = 0;
    var lastScrollTop = 0;
    var dontHandle = false;
    $("#home").scroll(function () {
    if (dontHandle) return;
        dontHandle = true;
        var st = $(this).scrollTop();
        (st > lastScrollTop) ? numberofscroll++ : numberofscroll--;
        console.log(numberofscroll);
        console.log(lastScrollTop);
        console.log(st);
        if (numberofscroll<2){
            change_background2(numberofscroll);
        }
        else if (numberofscroll<3){
            change_background3(numberofscroll);
        }
        else if (numberofscroll<4){
            change_background4(numberofscroll);
        }
        else if (numberofscroll<5){
            change_background5(numberofscroll);
        }
        else if (numberofscroll<6){
            change_background6(numberofscroll);
        }

        lastScrollTop = st;
        if (isFirefox == true) {
        window.setTimeout(function() {
            dontHandle = false;
        }, 150);
        }else if (isOpera == true) {
        window.setTimeout(function() {
            dontHandle = false;
        }, 10);
        }else if (isChrome == true) {
             window.setTimeout(function() {
            dontHandle = false;
        }, 10);
        }else if ($(window).width() < 480){
         window.setTimeout(function() {
         dontHandle = false;
        }, 500);
        }else { 
            window.setTimeout(function() {
            dontHandle = false;
        }, 50);
        }
    });

/images swaping code here/

});

I also attempted to incorporate the following addition which unfortunately did not yield the desired outcome:

    if ($(window).width() < 480){
     window.setTimeout(function() {
     dontHandle = false;
    }, 500);
    }else { 
    window.setTimeout(function() {
     dontHandle = false;
    }, 50);
    }

Answer №1

The process is determined by how the if-else if-else structure operates. If any condition is met, the subsequent conditions will not be evaluated. For example, in a scenario where you are using Chrome with a width of 300px:

if (isFirefox == true) {
  ...
}else if (isOpera == true) {
  ..
}else if (isChrome == true) {
  ...
}else if ($(window).width() < 480){
 ...
}else { 
  ...
}

In this case, it will stop at isChrome == true being true, skipping the following checks including the browser width evaluation. To resolve this, prioritize the width check to ensure it is always examined first before determining the type of browser.

if ($(window).width() < 480) {
  ...
}else if (isOpera == true) {
  ..
}else if (isChrome == true) {
  ...
}else if (isFirefox == true){
 ...
}else { 
  ...
}

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 methods with JavaScript, Ajax, or jQuery can I apply to populate the student details?

For completing the StudentID section, please fill out the form data.cfm with the first name, last name, and Middle Name. <script language="Javascript"> $(function() { $( '#effective_date' ).datepicker(); jQuery.validator.addMetho ...

Using JavaScript closures together with a timeout in the onKeyUp event

My goal is to add an onKeyUp event to all input fields within a form using closures. The array fields holds the names of the fields that need this event, while the array ajaxFields contains the names of fields requiring ajax validation. function createEve ...

Experiencing difficulty in choosing an array in Javascript

Currently learning Javascript and working on a project that involves retrieving data from a weather API. Encountered a simple issue that I need help with. Here is the data I managed to fetch so far: {coord: {…}, weather: Array(1), base: "stations", mai ...

Combining Turn.js with AJAX for an interactive web experience

I've been experimenting with turn.js and struggling to find an example of loading dynamic pages with content via ajax. While the page is loading, it's not displaying all the results. For a JSON result from the controller, click here. <div clas ...

Issue with React useCallback not being triggered upon a change in its dependencies

useCallback seems to be capturing the wrong value of its dependency each time. const [state, setState] = React.useState(0); const callback = React.useCallback(() => { console.log(state); // always prints 0, why? }, [state]); React.useEffec ...

Compatibility issues with jQuery observed in Firefox and Internet Explorer 11

Check out the code here: jsfiddle demo HTML CODE: <div class="first"> <!-- Part one --> <div class="acord_col"> <div class="img_class" id="exist_site"></div> <div class="intro_text"> </div> </div&g ...

I can't see any tools anywhere on my page in Literally Canvas

My Implementation: <!DOCTYPE html> <html lang="en"> <head> <title>Creative Drawing Tool</title> <link href="css/creative-drawing-tool.css" rel="stylesheet"> <script src="jquery-2.1.4.min.js"></scrip ...

Assume we have two positive integers, N and X. In this scenario, N represents the total number of patients, while X denotes the time duration, measured in minutes, between the arrival

Suppose you are given two positive integers N and X. Here, N represents the total number of patients while X indicates the time duration (in minutes) after which a new patient will arrive. The doctor only provides 10 minutes to each patient for consultatio ...

When clicking on an image, it triggers a unique PHP query, however the results obtained are not accurate

Greetings, I have a search feature on my website. When a user inputs a keyword and clicks the search button, it directs them to jobsearch.php which then displays a list of relevant jobs from the MySQL database. The functionality is working perfectly. Howe ...

Could this be a problem with synchronization? Utilizing Google Translate to link-translate terms

Trying to create a script that will show how a word changes through multiple translations using Google Translate, but struggling with Javascript. The problem I'm facing is hard to pinpoint: function initialize() { var word = "Hello"; var engl ...

The Material-ui Drawer does not function properly when used with an external CSS file

For my project, I'm working on a Sidebar design that is inspired by the Mini Variant drawer demo available at this link. However, the project requirements mandate that all CSS styling should be done in a separate CSS file rather than directly within t ...

Error: Unable to access 'author' property as it is undefined

Currently, I am in the process of learning how to create my own blog by following a tutorial on Github. The tutorial can be found at https://github.com/adrianhajdin/project_graphql_blog. However, while working with [slug].js to build localhost/3000/post/re ...

Exploring the utilization of attributes with slots in Vue.js

Can attributes be set on a slot so that the element from the parent inherits those attributes? Parent <vDropdown> <button slot="button">new button</button> <ul>content</ul> </vDropdown> Dropdown.vue <d ...

What could be the reason for the defaultCommandTimeout not functioning as expected in my script

Is there a way to wait for only one particular element in Cypress without having to add wait commands everywhere in the test framework? I've come across the solution of adding defaultCommandTimeout in the cypress.json file, but I don't want it t ...

TypeScript throws an error when jQuery is imported unexpectedly

How does the compiler resolve the $ in the code snippet below, even without importing jQuery? function f () { $('#loadFiles').click() // ok $$('#loadFiles').click() // error, can't find name '$$' } The compile ...

"Enhance your website with a dynamic hover effect and striking letter spacing in

In the div below, there is a span with the following code: <div class="mission-button"><span class="mission">view our mission</span></div> Accompanied by this CSS: .mission-button::before { content:'&ap ...

Enhancing jQuery UI Tabs with HoverIntent

I'm currently working on incorporating HoverIntent into my jQuery tabs, but I seem to be facing some issues. Below is the code snippet that I've been using. Any suggestions or tips would be greatly appreciated. Thank you! The code was sourced di ...

Incorporating database row data into JavaScript objects: a guide

Here's a question that has me stumped and seeking help. Following an ajax send request, I utilized this php code to retrieve all the rows and columns from my database: $sql = "SELECT * FROM categories"; $result=$conn->query($sql); $arr = $resul ...

AJAX using PHP returns an object containing null values

As a beginner in ajax programming, I encountered a small issue. I created a function in jQuery that makes an ajax call to a PHP file, which then retrieves information about a player from the database. However, when the PHP file responds to the ajax functio ...

Fade between two divs using jQuery works perfectly with images, but unfortunately, it does not work with iframes

Edit: Uploaded live, with images, and with iframes I am experimenting with making pane1 fade into pane2. It successfully works with images, but I am curious if it can be achieved with iframes. Is this feasible? Any insights or suggestions are much appreci ...