Try using 'img src' as the background image

I am attempting to set the background-image using img src when media queries are activated.

My media queries kick in at a max-width of 854px.

I have been trying to achieve this with jQuery but it doesn't seem to be working.

This is my jQuery code:

$(document).ready(function () {
        if ($(window).width() <= 854) {
            $('a.class').css('background-image', 'url(' + $('a.class img').attr(src) + ')');
        }
    });

Can someone please help me figure out what I am doing wrong?

Thank you!

Answer №1

When using jQuery to accomplish this task, the following code may be helpful:

$(document).ready(function () {
    if ($(window).width() <= 854) {
        $('a.class').each(function(){
            $(this).css('background-image', 'url(' + $(this).children('img').attr('src') + ')');
        });
    }
});

I opted for an each loop in anticipation of potentially having multiple instances of a.class, and I chose to use quotes for the src attribute.

Answer №2

Modification

$('a.class').css('background-image', 'url(' + $('a.class img').attr('src') + ')');

transform to

$('a.class').css('background-image', 'url(' + $('a.class img').attr('src') + ')');

The .attr function necessitates a string. It was necessary to enclose the value in quotes as src signifies the attribute's name.

If you were to check your browser's consoles for errors, as advised by Juan, you would have likely caught this mistake. Alternatively, if you examined the syntax highlighting in your IDE, you would have observed that src was highlighted as a variable rather than a string.

Answer №3

$('a.element').css('background-image', 'url(' + $('a.element img').attr("src") + ')');

The "src" attribute must be enclosed in quotation marks.

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

Using regular expressions in JavaScript to work with numbers separated by commas, as well as their comparison operators such as greater than, greater than or

Currently, I have implemented this Regex pattern to validate numbers with decimals (comma separated) /(^\d*\,?\d*[1-9]+\d*$)|(^[1-9]+\d*\,\d*$)/ However, I am now faced with the need to modify it in order to also valida ...

Is there a way to enable Fancybox to change to the adjacent gallery by simply using the 'up' or 'down' arrow keys?

I am currently working on a layout that consists of a vertical column of thumbnail images, each linked to its own gallery with additional images. When the user clicks on a thumbnail image, Fancybox opens, allowing them to navigate through the images within ...

Strange symbols keep appearing in my output from PHP

My current task involves generating a SQL query based on some inputs. I have a predefined SQL statement, in which I perform certain replacements, that will use these inputs to generate the required SQL through an ODBC connection. For now, I have stored th ...

Working with AngularJS: binding data to dynamically appended HTML elements using JavaScript

Is there a way to connect an angular event and model to an html element that is added through javascript code? To see my code, click here: https://jsfiddle.net/hq7qk48n/13/ <div ng-app> <div ng-controller="MyController"> <input ...

Incorporating React into an existing jQuery single page application

My current dilemma involves transitioning from a jQuery-built single page app to React. The challenge I'm facing is that, when building sections at a time, issues arise during the process. One major obstacle is the necessity of passing in a parent "r ...

Start fresh with the count for every individual table

In my HTML document, I have multiple tables with columns that have classes "valuation" and "valuation_all". If one cell in the "valuation" column contains the text "FAIL", then the corresponding cell in the "valuation_all" column should display "FAIL"; oth ...

The Ajax post function is not functioning as expected

Here is my code: $.ajax({ type: "POST", url: "mailyaz.php", data: { name: "testest" } }); Currently, the code works with a simple message of "testest". However, I am trying to post my javascript variable (var mysubjec ...

Combining the results of two separate API requests using jQuery/ajax

Hello there, Internet World! This is my first post here, so please be kind. I have gained a lot of valuable knowledge from this site so far, and now I am in need of some help. I have experimented with various code variations such as $when & $then, fu ...

Assigning the CSS class "active" to the navigation menu in ASP Classic

Seeking assistance with setting a CSS class for the current page in an include file that contains the primary navigation menu. Here is my current progress: public function GetFileName() Dim files, url, segments, current 'obtain c ...

How can multiple buttons be added to each row in Jquery datatables and how can events be applied to them?

I currently have one button, but I am in need of two buttons. These buttons will trigger MySql commands when clicked to retrieve data from the database. How can I set up an event handler for these buttons? $(document).ready(function () { var table= ...

What is the most efficient way to find the parent element with the fewest children?

In close proximity are two containers, each containing a series of smaller containers. <ul class="containers"> <li>Matt</li> <li>John</li> <li>Mark</li> </ul> <ul class="containers"> &l ...

Utilize ASP.net to efficiently store and retrieve events in a SQL database

If you have an SQL database table named Calendar, here are the tasks you may want to accomplish: You can achieve the following using Ajax: Retrieve events from the database and pass a List to your website. Save events back to the database. Note that ev ...

Header with Sticky Behavior and Smooth Slide Down Animation

I am trying to achieve a scroll effect on my page where the header will move up when scrolling up, but at position 150 it should smoothly slide down and stay fixed at the top. I have tried various methods but haven't been able to get it right. Can som ...

Problem arising from animation not commencing at expected starting point

Creating a feature on an app that involves breathing exercises using CSS animations. The challenge I'm facing is ensuring the words "exhale" and "inhale" appear synchronously with the animation of a circle shrinking and enlarging. However, the animati ...

The dynamic addition of the active class is malfunctioning

I have dynamically added a class using AngularJS, but it seems to not be functioning correctly. As I am new to AngularJS, I would appreciate any suggestions to resolve this issue. Below is my HTML code: <div class="col-md-15 col-sm-3" ng-repeat="data i ...

Modify a value using jQuery

On my Asp.net webform, I have a label called "LabelTotalNumber". I am looking to update the value of this label every minute using jQuery without having to refresh the form. How can I achieve this? Currently, I am able to accomplish updating the value onc ...

Click on the link to access and activate the function

Currently, I am retrieving values from a text input field. Using jQuery: $('.submitLocation').click(function(){ // grabbing value from the input field var city = $(".city").val(); }); For HTML: <input type="text" name="city" class ...

Develop a PHP and Mysql PDO application integrated with MSSQL, JSON, jQuery, and DataTables for

Presently, I am engaged in a project where I initially started working with MySQL using Xampp. However, at this point, I wish to transition to MSSQL. Although I successfully established the connection string, I am encountering an error when utilizing datat ...

Unexpected type error in jQuery widget while attempting to read a property of undefined using the $.ajax() method with .abort()

After creating a widget that utilizes an $.ajax() call to retrieve data from the server, I faced a challenge. I needed to enable users to refresh the data on demand, while ensuring that only one request is executed at a time to avoid conflicts with multipl ...

The event listener for 'click' will only function once

Having trouble with what may seem like a simple issue. The button event (code below) only functions once and then stops working on subsequent clicks. I have coded the desired behavior in the first if statement of the blur function, but since it doesn' ...