Hide image URL on mobile devices with CSS and JavaScript

Exploring the realm of cross-device magic, I have a challenge on my hands. My goal is to eliminate a slider image for screen widths smaller than 622px. Through experimentation, I have discovered that removing the image URL in CSS achieves the desired effect.

Here's my strategy...

I plan to enqueue a .js file in Wordpress to monitor when the screen size dips below 622px, and then utilize .js to alter the CSS by removing the slider image URL.

My action plan...

Add the script in functions.php

function wpb_adding_scripts() {

    // Register and Enqueue a Script
        wp_register_script('screensizemods', get_stylesheet_directory_uri() . '/js/screensizemods.js');
    wp_enqueue_script('screensizemods');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );

My script /js/screensizemods.js

function Resize() {
     width = window.innerWidth;
     height = window.innerHeight;

     if(width < 622) {
          // Adjust specific Stylesheet elements.

    document.styleSheets[0].addRule('background-image: url("");}');             
     }
}

Despite all efforts, it appears my approach isn't yielding results. No console .js errors are reported, and the script is successfully loaded. Could there be an issue with my .js code?

Edit:

This is the element I'm attempting to modify, which seems to be rendered inline by the Theme...

element {
    background-image: url("http://www.example.com/wp-content/uploads/2015/05/bgimage.jpg");

Edit 2:

Streamlining things with a media query watcher attempt...

The media query is triggering correctly upon screen resize. However, an error

reference error: style is not defined
is encountered.

     // Media Query Event Handler
    if (matchMedia) {
    var mq = window.matchMedia("(min-width: 622px)");
    mq.addListener(screensizemods);
    screensizemods(mq);
    }

    // Media Query Change
    function screensizemods(mq) {

    if (mq.matches) {
        // Window width exceeds 622px
    }
    else {
        // Window width less than 622px
            // Apply a new rule to the top of my stylesheet
            style.css.insertRule("background-image: url('') !important}", 0); 
    }

}

Answer №1

The most effective way to address this issue is by utilizing CSS @media queries, commonly referred to as "responsive design".

For more information on CSS Media Queries, you can visit this link.

element { background-image: url(http://www.example.com/wp-content/uploads/2015/05/bgimage.jpg); }

@media (max-width: 622px) {
    element { background-image: none; }
}

Answer №2

Kindly review the following code snippet, it may be beneficial for you.

Below are two solutions provided:

1) CSS solution:

<style>
element {
    background-image: url("http://www.example.com/wp-content/uploads/2015/05/bgimage.jpg");
}

@media (max-width: 767px) {
    element { background-image: none; }
}
</style>

2) jQuery solution:

<script type='text/javascript'>
    function checkWidth() {
        //check window width when function call.
        var windowSize = jQuery(window).width();

        if (windowSize <= 767) {
            // remove image for small size window screen.
            jQuery( 'element' ).css('background-image', 'none');
        }else{
            // add image for big size window screen.
            jQuery( 'element' ).css('background-image', 'url(http://www.example.com/wp-content/uploads/2015/05/bgimage.jpg)');
        }
    }

    jQuery(document).ready(function () {
        checkWidth();
        jQuery(window).resize(function(){
            // on window resize call function to check window width.
            checkWidth();
        });
    });
</script>

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

Modifying language in Kendo UI

I am currently using Kendo UI to develop grids and applying the data-filterable option for data filtration. My requirement is to switch the language from English to Polish. How can I achieve this? https://i.sstatic.net/J5PEa.png Below is the script I am ...

Creating an icon on the right side of a Bootstrap panel: A step-by-step guide

Seeking assistance with aligning a cool icon within a bootstrap panel. I am trying to position this icon on the right side of the panel heading, but the code is not cooperating. Can anyone provide guidance? <div class="panel panel-primary"> < ...

Step-by-step guide: Crafting an UP Arrow solely with HTML and CSS

What is the method to utilize solely HTML and CSS for creating a triangle? I am in need of constructing a thick triangle, but want to achieve this using only CSS So far, I have experimented with the following code: .arrow-up { width: 0; height: 0 ...

Implementing a collapsible menu feature in Bootstrap 3 when clicked

Experiencing an issue with a Bootstrap menu where I want the menu to collapse after clicking on one of the sections. This is the HTML code: <div class="container" id="home"> <nav class="navbar navbar-default navbar-fixed-top" role="navig ...

Difficulty with aligning textfield controls to the right

I'm currently working on adding StaticTextField controls to a page. We are using ExtJS, but we incorporate VB.NET methods for implementing ExtJS so manual coding isn't necessary. So far, I attempted to align the text to the right by using this c ...

Getting WordPress custom widget settings through AJAX

I'm currently in the process of developing a custom widget for WordPress. The main purpose of this widget is to showcase a specific item associated with a Custom Field that I have configured within the platform. However, I've encountered some ch ...

Error encountered while trying to store a JSON object in local storage

When attempting to insert a JSON in localStorage, I am encountering the error Unexpected token ~ in JSON at position 3 during the parse process. Here is how I am inserting the data into localStorage: localStorage.setItem( "users", `"[\"~#iM& ...

Issue encountered while running the TestCafe Docker Image within a GitLab CI job. Attempting to run automated end-to-end tests on BrowserStack

We are currently attempting to execute end-to-end tests using testcafe on BrowserStack triggered by a gitlab CI job. Unfortunately, an error keeps appearing: Error: spawn /home/user/.browserstack/BrowserStackLocal ENOENT Our approach involves implementin ...

Is there a way to send a Razor boolean variable to an Angular directive?

Within my cshtml file, I am working with a boolean variable. However, when attempting to pass this variable to my Angular directive, it is being received as "False" rather than "false". Even hardcoding it to be "false" in lowercase does not solve the issue ...

The jQuery execCommand feature fails to generate a pop-up when used within the contenteditable attribute of an HTML tag

Trying to implement an inline text editor using the jQuery execCommand function. Below is a snippet of my source code: /*******************************************************************/ /********** Click: inner of contenteditable text-editor div *** ...

Is there a way to automatically zoom in when clicking on a marker and centering the map to that

I have integrated a map into my project where I am currently plotting random coordinates. These coordinates are stored in a data table and everything is functioning smoothly. However, I am facing an issue with implementing a zoom feature using the panTo m ...

Creating formGroups dynamically for each object in an array and then updating the values with the object data

What I am aiming to accomplish: My goal is to dynamically generate a new formGroup for each recipe received from the backend (stored in this.selectedRecipe.ingredients) and then update the value of each formControl within the newly created formGroup with t ...

JavaScript date input formatting with HTML

When using the input date picker in HTML, the default format displayed is MM-DD-YYYY. <input type="date" id="gdatum" /> Is there any method to change the mask to DD-MM-YYYY? ...

The active class in Bootstrap 4 Scroll Spy failed to update

My HTML code: <body data-spy="scroll" data-target=".dmu-top-nav" data-offset="50"> <header> <nav class="navbar navbar-toggleable-sm navbar-expand-md dmu-top-nav fixed-top" role="navigation"> <div class="container-fluid"> &l ...

Troubleshooting Hover Problem with D3 Chord Example on Internet Explorer 11

I came across an interesting tutorial on how to create chord diagrams in D3, which I'm currently experimenting with. The tutorial can be found at One example that caught my attention is about hair color preferences. When you hover over a group on the ...

Changing the response body before calling res.send() in ExpressJS

Currently, the application I am working on utilizes Express. My goal is to intercept the response before it is sent and modify it for JWT purposes. With numerous endpoints in this application, I am looking for a way to achieve this without creating a custo ...

React functional components with checkboxes can trigger rerenders

I'm currently working with Gatsby and have a functional component that iterates through a set of data to generate a radio button group with an onchange event and a checked item. Whenever I update the state, the entire page component re-renders. I thou ...

The function does not get activated when mouseover event is triggered with AddEventListener

I am attempting to create a series of radio buttons, each with its own AddEventListener function. However, I am encountering issues while using the code below within a while loop that retrieves data from a MySQLI table: echo ' <script> do ...

What is the best way to refresh or manually trigger the marker cluster icon update in Google Maps API?

Recently, I implemented a custom cluster HTML marker, where I attempted to dynamically change the color of my markers within the cluster. Despite debugging the code and confirming that the color variable was being updated correctly, the marker colors thems ...

Strategizing the incorporation of a border bottom implemented with an hr tag

I am attempting to create something that looks like this: https://i.sstatic.net/XXwFg.png However, my current implementation only results in this: https://i.sstatic.net/a8f6u.png Below is the code I have been using: <div class="col-md-12" ...