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

Explore our array of images displayed in an interactive gallery featuring clickable

I have a query I'm facing an issue with my code. Currently, I have a gallery that displays images perfectly. Now, I want to enhance it by showing a larger resolution of the image when clicked. However, when I add the href tag to link the images, they ...

Is there a way to dynamically integrate the Insert Column feature into the ContextMenu of a Syncfusion Treegrid?

What is the best way to add Insert Column functionality to the ContextMenu of a Syncfusion Treegrid? Insert Column Rename Column Delete Column ...

Retrieve the route from a specific node in the jstree structure

Looking to retrieve the paths of selected nodes in jstree? You'll need the complete path of the nodes. I have a php file that generates the JSON, structured like this: header("Content-Type: application/json; charset=utf8"); echo json_encode(dir_to_ ...

Creating the x and y coordinates for drawImage in HTML5

Understanding the x and y axis has posed a challenge for me: //retrieve last known x and y coordinates ...code var p = $("#draggable"); var offset = p.offset(); var x = offset.left; var y = offset.top; //establish new font siz ...

Synchronize data with Microsoft AJAX using force sync

When working with the Microsoft AJAX framework, I encounter a problem where my AJAX calls are asynchronous when I actually need them to be synchronous. I'm struggling to find a solution for this issue. In addition, I have been having difficulty findi ...

Simplified method for creating Angular templates

Take a look at this code snippet my_app.run( [ '$templateCache' , function( $templateCache ) { var template = "" + "{{ item.name }}" + "<ul ng-if='item.sub'>" + "& ...

Filtering an array of parent elements in Javascript based on a specific value found in

Trying to filter data from a 3-layer array based on child array values. Making progress but hitting a roadblock at the end. { "id": 1, "grandparent": "Timmy", "parents": [ { "id&q ...

Discover the job specifications pages on Dice.Com by utilizing C programming language

I have taken on a student project involving web scraping job postings from Dice.Com for analysis. My main focus is on extracting the job description, but I am struggling to figure out how to access it. With limited knowledge in HTML and C#, I find it dif ...

What is the best way to use jQuery to listen for a container resizing event?

I am confident that I can achieve this: $(window).resize(function() {funkyfunc();}); The above code will execute funkyfunc() whenever the window is resized. However, my issue lies in wanting to resize one control after another has been resized. I've ...

Ways to stop the floating label from blending with the input field

Attempting to incorporate the Bootstrap Material design theme into my project, I have implemented a basic text input field using the code below: <div class="form-control-wrapper"> <input class="form-control empty" type="text"></input> ...

What is the best way to filter and sort a nested tree Array in javascript?

Looking to filter and sort a nested tree object for a menu If the status for sorting and filtering is true, how do I proceed? const items = [{ name: "a1", id: 1, sort: 1, status: true, children: [{ name: "a2", id: 2, ...

Is there a way to iterate through an array in reverse, starting from the last element and ending at the first element?

Is there a way in JavaScript to map an Array starting from the last index and going all the way to the beginning descending, without iterating from the beginning index? I'm looking for a more efficient method or feature I might have overlooked. Any s ...

Hoping for a swift ajax response from the identical function

Even though similar questions have been asked multiple times, I have gone through many of them and still haven't found a solution to my specific issue. I am currently using a Wizard Jquery Plugin that triggers a function onLeaveAStepFunction when a s ...

How can I design a form that resembles the sign-in form used by Google?

Currently, I am in the process of creating a contact form for a website that is inspired by the design of Google's material sign-in form. I have successfully implemented an effect where clicking on the input field causes the label to change its posit ...

Executing multiple HTTP requests simultaneously in groups using an asynchronous for loop for each individual request

I'm currently working on running multiple requests simultaneously in batches to an API using an array of keywords. Read Denis Fatkhudinov's article for more insights. The issue I'm facing involves rerunning the request for each keyword with ...

I'm having trouble seeing the values displayed above the bars in Chart.js

Recently, I started learning about chart.js and encountered an issue where the bars were not displaying the values on top, along with a question on how to add a percentage sign after the value. I'm using chart.js version 3.3.2 from a CDN. Any assistan ...

Does implementing a product listing with filter, sorting, and search options through Ajax violate any REST principles?

As I work on creating a product listing library for a web application, it's crucial to incorporate filter, search, and sort functionalities. A web service is available that can fetch results based on these parameters, including page number and product ...

Ag-Grid is failing to display MenuTabs

I need help getting the columns menu tab to appear in Ag-Grid. It should be a simple task. I want both the general and columns tabs, similar to the demo shown here Currently, when I specify both tabs, only the general tab is displayed. If I specify just t ...

The process of setting up a carousel for tables using jQuery

I can successfully implement jquery for an image carousel, but now I need to find a way to create a sliding table format. Any assistance on this matter would be greatly appreciated. Here is the code I currently have: <ul> <li><a style= ...

Refresh the custom JavaScript dropdown list without having to reload the page

I implemented this code to customize a drop-down list Selector. Is there a way to reset this code without reloading the page, maybe by triggering a function with a button click? <button onclick="reset();">Reset</button> For example, if "Jagu ...