Toggling javascript functionality based on media queries

On one of my slides, I want to display images that are specific to different devices like iPhone, iPad, and desktop.

I am looking for a way to filter these images based on the device. Using display:none won't work as it's JavaScript, but here is a basic idea of how it could be done:

<style type="text/css">
@media only screen and (min-width: 800px) {
    #slide-desktop {display:block;}
    #slide-ipad {display:none;}
    #slide-iphone {display:none;}
}
@media only screen and (min-width: 481px) and (max-width: 799px) {
    #slide-desktop {display:none;}
    #slide-ipad {display:block;}
    #slide-iphone {display:none;}
}
@media only screen and (max-width: 480px) {
    #slide-desktop {display:none;}
    #slide-ipad {display:none;}
    #slide-iphone {display:block;}
}
</style>
<div id="slide-desktop">
    <script>
        $.vegas('slideshow', {
        delay:6000,
        backgrounds:[
        { src:'images/slide/desktop.jpg', fade:600 },
        ]
        })('overlay');
    </script>
</div>
<div id="slide-ipad">
    <script>
        $.vegas('slideshow', {
        delay:6000,
        backgrounds:[
        { src:'images/slide/ipad.jpg', fade:600 },
        ]
        })('overlay');
    </script>
</div>
<div id="slide-iphone">
    <script>
        $.vegas('slideshow', {
        delay:6000,
        backgrounds:[
        { src:'images/slide/iphone.jpg', fade:600 },
        ]
        })('overlay');
    </script>
</div>

Answer №1

To execute different scripts based on a media query, consider using the enquire.js library.

With enquire.js, you can easily respond to CSS media queries using a lightweight and pure JavaScript approach.

This means you won't have to include any styling within your code.

Answer №2

If you need to determine the device width using JavaScript, you can utilize a simple script like the one below:

   if(window.innerWidth >= 800)
   {
     alert('Is this a desktop?');
   }
   else if(window.innerWidth >= 481 && window.innerWidth < 799)
   {
     alert('Could this be an iPad?');
   }
   else if(window.innerWidth < 480)
   {
    alert('Possibly an iPhone?');
   }

Nevertheless, I would recommend exploring other methods rather than solely relying on this approach. Take a look at

The optimal technique for detecting a mobile device in jQuery.

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

Text overlapping image causing hover state interference

I'm feeling completely lost right now. My goal is to have the title of each project displayed in the center of the screen when you hover over the respective project images. I've resorted to using jQuery for this because it seems like the most str ...

Is it possible to dynamically alter the text and contrast of your entire website?

In the realm of MVC 4 and Visual Studio 2013: I am pondering over how to dynamically change the text on my website with the simple click of a button. The same goes for adjusting contrast. Are there any plugins or techniques that could facilitate this proc ...

Is there a more efficient method for writing my jQuery code that follows a step-by-step approach?

I have developed a step-by-step setup process that guides users through various sections. Instead of using separate pages for each step (like step1.php, step2.php, etc.), I have all the code contained in one page named setup.php. This is achieved by utiliz ...

What is the best method for extracting span text using selenium?

<p id="line1" class=""><span class="bot">Do you have a short-term memory?</span><span id="snipTextIcon" class="yellow" style="opacity: 1;"></span></p> I want to extract this text: Do you have a short-term memory? This ...

Run custom JavaScript code dynamically within a webpage

What is the most effective way to use Java to automatically open a web page, run some JavaScript to complete and submit a form, and analyze the outcome? ...

Is there a way to modify the CSS of the sequential number element when it is clicked on?

I've successfully utilized jQuery to create sequential numbering for my menu items. Upon clicking, the hyperlink text changes color to red. However, I'm facing an issue where I want the corresponding number to also change to red when the hyperli ...

Navigating cross domain JSONP cookies in IE8 to IE10 can be a real headache

For reasons completely out of my control, here is the current scenario I'm faced with: I have a product listing on catalog.org When you click the "Add to Cart" button on a product, it triggers an AJAX JSONP request to secure.com/product/add/[pro ...

Changing the click event using jQuery

My JavaScript snippet is displaying a widget on my page, but the links it generates are causing some issues. The links look like this: <a href="#" onclick="somefunction()">Link</a> When these links are clicked, the browser jumps to the top of ...

The data received from the frontend is being replicated in the backend, causing duplication issues in a React

Whenever I click the button labeled onClick, it triggers the transmission of data (both time and ID) to the backend. The issue at hand is that the backend seems to be receiving the data twice instead of just once. On inspecting req.body, it becomes eviden ...

"Encountering difficulties while setting up an Angular project

I am currently working on setting up an Angular project from scratch. Here are the steps I have taken so far: First, I installed Node.js Then, I proceeded to install Angular CLI using the command: npm install -g @angular/cli@latest The versions of the ...

What is the best way to create a distinct key for the key prop in my map function within a React component?

This is the initial code I have: class Board extends Component { static defaultProps = { nrows: 5, ncols: 5, chanceLightStartsOn: 0.25 }; constructor(props) { super(props); this.state = { hasWon: false, board: this. ...

Problem importing npm module with Meteor 1.3

I've been trying to follow the guide for using npm packages in Meteor 1.3, particularly focusing on installing the moment npm module. However, I can't seem to work it out despite its simplicity. Every time I attempt to use the package in the cli ...

Include IE-specific stylesheet code in your Angular application (version 1.2)

I would like to implement conditional IE CSS for IE8 and IE9 in my Angular application. The approach I took was to add the specific CSS files directly in the index file as shown below: <!-- Application main stylesheet --> <link href="styles/them ...

Is it possible to create two separate Express sessions simultaneously?

I am encountering an issue with my Passport-using application that has a GraphQL endpoint and a /logout endpoint. Strangely, when I check request.isAuthenticated() inside the GraphQL endpoint, it returns true, but in the /logout endpoint, it returns false. ...

Adding a Fictitious Pair to a JavaScript Object Literal

When I work with object literals in JavaScript, I often encounter syntax errors when adding a new label / value pair without including the trailing comma. This can be frustrating as it's easy to forget to include the necessary delimiter. .draggable({ ...

Vue: Issue with Firebase Authentication REST API triggers 400 Bad Request Error

Here is the error message I am encountering: POST scheme https host identitytoolkit.googleapis.com filename /v1/accounts:signUp key AIzaSyAk1ueCLjDDWCNrt_23o5A4RCfeaYIlN6k Address 74.125.24.95:443 Status 400 Bad Request VersionHTTP/3 Transferred850 B ...

What steps should I follow to obtain the return value after invoking these functions?

I have a task that requires creating a nodejs script for two specific functions: Retrieve my public IP address. Update my public IP address on my freenom.com account for a registered domain. Currently, I have two separate scripts in place to accompl ...

Having difficulty sending variables to onreadystatechange

Here is the latest version of the source code: var xhttp = new XMLHttpRequest(); function passVars(var1, var2, var3) { if (var1.readyState == 4) { if (var1.status == 200) { var data = var1.responseText; if (data) { playSuccess ...

Disable the meta tags in Zurb Foundation 5

I have searched extensively online but haven't been able to find a solution for this issue. How can I disable these zurb foundation 5 meta tags in the <head>: <meta class="foundation-mq-small"> <meta class="foundation-mq-small-only"> ...

Implementing Security Measures for ExpressJS Static File Server

Recently, I set up an authentication system following a tutorial on express.js and passport.js. In the past, my express server setup used modRewrite as shown below: var express = require('express'); var modRewrite = require('connect-mod ...