Unable to modify the background image of a div using jQuery

I'm encountering an issue in my script where I tried to implement an event that changes the background-image of a div when a button is clicked, but it's not functioning as intended.

Below is the code snippet:

HTML

<div class="col-md-2 imageCard" style="float:left">
            <img class="card-img-top"
              src="https://mdbootstrap.com/img/Photos/Horizontal/City/4-col/img%20(60).jpg" alt="Card image cap">
</div>

<div class="card-body">
          <blockquote class="blockquote mb-0">
            <p id="quoteSample">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p>
            <footer class="blockquote-footer" id="quoteAuthorSample">Someone famous in </footer>
          </blockquote> 
</div> 

JS

$('.imageCard').click(function(){
    var imageSRC = ($(this).children('img').attr('src'));
    console.log(imageSRC)
    $('.card-body').css("background-image", "url(" + imageSRC + ")")
})

The output from console.log shows:

Answer №1

It seems like the $('.imageCard') button element is not being detected by the script when it tries to set the event listener (in this case: click).

To resolve this issue, you have a couple of options:

  1. Consider placing your script tag at the bottom of the page so that it loads just before the HTML, allowing it to locate the button that has already been rendered.
  2. Alternatively, you can attach your jquery click within a window load event handler, as shown below:

    $(document).ready(function() {
        // Jquery click event
    });
    

    This approach ensures that your javascript DOM code executes only after the document (HTML page) has finished rendering completely

I hope this information proves helpful!

Answer №2

After some investigation, I discovered the issue lies in the way the concatenation assignment is being handled for the background-image CSS property. While this property can accept a URL by using the url() function, it is important to note that the argument passed to url() should be a string. Although this approach works seamlessly in vanilla JavaScript, when you are adding this property through a function (using strings as parameters), extra caution is required to ensure the correct output. Here is an illustration of how to handle this situation (you can experiment with this in your browser console):

Firstly, assign a link to a variable:

    var imageSRC = "https://mdbootstrap.com/img/Photos/Horizontal/City/4-col/img%20(60).jpg"

Simply running the following line will result in:

    "url(" + imageSRC + ")" // "url(https://mdbootstrap.com/img/Photos/Horizontal/City/4-col/img%20(60).jpg)"

Now, observe the link within the url() function - it is no longer treated as a string but rather as plain text, which doesn't comply with the requirement for url() to receive a string.

To rectify this issue, you have two options:

  1. Instead of using "url(" + imageSRC + ")", opt for "url('" + imageSRC + "')" to ensure the correct quotes are applied to the parameter.
  2. Alternatively, utilize JavaScript template strings (more information available here: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/template_strings)

    `url("${imageSRC}")`
    

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

Attempting to transmit multiple variables

Can anyone provide assistance with passing multiple variables from one page to another? I am able to pass a single variable, but I need to send more than one by clicking a link. Below is a snippet of my code containing the rows I want to transmit to the ne ...

Guide to adding an icon within an HTML `<input>` element

Is anyone able to help me successfully place my icon font inside the search input field? I've tried adjusting the margin and padding, but nothing seems to be working! If you have any insights or suggestions, please let me know. Your help is greatly a ...

Nested loops combined with a timeout occasionally results in failure

I encountered a problem with the loops and timeouts in my script that I created for practice. If you want to take a look at the script, you can find it here: http://codepen.io/JulienBarreira/pen/EWNoxJ When running the script, I noticed that sometimes one ...

Is there a way for me to set distinct values for the input box using my color picker?

I have two different input boxes with unique ids and two different color picker palettes. My goal is to allow the user to select a color from each palette and have that color display in the corresponding input box. Currently, this functionality is partiall ...

What is the best way to incorporate this code snippet into an object's value?

Is there a way to merge the headStyles object into the headText object? I have already injected the headStyles object into headConfig. import { makeStyles } from '@material-ui/core' const headStyles = { backgroundColor:'green', ...

Refreshing the page in Next.js causes issues with the CSS classNames

I am currently in the process of migrating a React SPA to Next.js, and I am relatively new to this framework. The issue I am encountering is that when I initially load the Home page, everything appears as expected. However, if I refresh the page, incorrect ...

MUI-Datatable rows that can be expanded

I'm attempting to implement nested tables where each row in the main table expands to display a sub-table with specific data when clicked. I've been following the official documentation, but so far without success. Below is a code snippet that I& ...

Locating the source of the function call within a file in Node.js

Is it possible to determine the location of a file if a method from a module is called within that file? For example: // my-module.js module.exports = { method: function () { // I would like to know the path to my-app.js here } } // my-other-mod ...

Chrome browser not responding to jQuery .html refresh

I am facing an issue with a page containing a list of tasks, each with a dropdown menu featuring a list of teams to which the task can be assigned. However, pre-populating the dropdown in the Action function is not feasible due to the large number of tasks ...

Implement JQuery to display a loading message whenever an a tag is clicked

The website's various pages are filled with standard <a> tags, some of which have a class attribute that is utilized for styling using CSS. Each <a> tag includes a href="" attribute linking to another page on the same site. My goal is to d ...

Is There a Way to Abandon a route and Exit in Express during a single request?

In order to ensure proper access control for the application I was developing, I structured my routing system to cascade down based on user permissions. While this approach made sense from a logical standpoint, I encountered difficulties in implementing it ...

I am encountering difficulties with hosting a project that was created using Next.js

I am currently working on a Next.js project and I encountered some version compatibility issues when integrating MUI. While my project runs smoothly in localhost, it fails to work when deployed in hosting. I attempted to resolve this by using the --legacy ...

Mastering the Art of jQuery Post with Iteration and Result Utilization

I am facing an issue with my code function fetchInfoFromDB() { let body = ""; let text = ""; $("tr").each(function (index) { let code = $(this).children("td:nth-child(2)"); $.post("http://urltogetdatafromdatabase.com/getinfo.ph ...

Is it possible for PHP to use the set cookie function to replace the cookie value set by JQuery cookie?

I'm facing an issue where I want a single cookie to be set and its value updated by PHP when a user logs in. However, currently it seems to just create a new separate cookie each time. Below is the code snippet where I am trying to set the cookie valu ...

Create a rectangle when the mouse is pressed down

Creating a zoomable and pannable canvas in Fabric.js was easy, but now I am facing an issue with accurately drawing a rectangle on each mousedown event. The problem arises when the canvas is transformed from its original state, making the coordinates inacc ...

How to enable seeking functionality for mp3 files with PHP

I have implemented the following PHP script: video tags are unable to extract metadata from it. Any insights on where I might be going wrong and how to rectify this situation? Your guidance would be greatly appreciated. Thank you.

...

Is d3 Version pretending to be a superior version?

I have encountered an issue with my project that involved using d3 v5.5.0. After transferring it to a different computer and running npm install, the application now seems to be recognizing d3 as a higher version? A crucial part of my program relies on th ...

Is there a simple solution to show script 1 to visitors from the US and Canada, while displaying script 2 to visitors from other countries?

I'm looking for a simple script that can show one script to visitors from the US and Canada, and another script to visitors from other countries. It doesn't have to be perfect, but using a service like seems too complex for me. Is there a stra ...

Visual Studio Code unable to locate source maps for typescript debugging

Looking for some help debugging a basic Hello World TypeScript file. Whenever I try to set a breakpoint, it seems like VS Code is having trouble locating the source map, even though it's saved in the same directory. I'm using Chrome as my browser ...

What's preventing it from being cached?

So, I have a website (https://illution.dk) and most of my files that are included or linked are returning a "304 Not Modified" header. However, there is one exception: https://illution.dk/include/style.php, which always returns a "200 OK." The headers for ...