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

The battle between Hover, Focus, and Blur modes intensifies

My goal is to implement 4 different effects on an element: When hovering over the element. When moving away from the element. When focusing on the element. When blurred. However, I'm encountering a conflict where when I focus on the element, the ...

Algorithmically alter the view of the webvr camera

I am looking to dynamically change the position of a view within a webvr scene. My approach involves using the position.add method. Below is the code snippet that demonstrates how I programmatically move the camera: <a-entity position="33 0 -33" rota ...

Is the trigger feature malfunctioning in Chrome?

Recently, I implemented a trigger function in order to enable another function by triggering the text box. Unfortunately, I am experiencing difficulties as it does not seem to be working properly on Google Chrome. Any assistance you can provide would be ...

The shown.bs.tab event is causing an issue where the previous active tab cannot be retrieved

Reference from https://getbootstrap.com/docs/4.0/components/navs/#events states that I am utilizing e.relatedTarget in the shown.bs.tab event to retrieve the previous active tab for applying some CSS styles. However, currently, e.relatedTarget is returning ...

- What are the steps to integrate a different JavaScript plugin into a React project?

Lately, I've come across an issue while trying to incorporate a 3rd party plugin into my practice project in Next.js. Considering that I'm fairly new to React, understanding the 'react way' of doing things has proven to be quite challen ...

Tips for adjusting slider values using jQuery or Capybara

I've been attempting to adjust the slider value, but I haven't been successful so far. I'm using Capybara with a selenium driver. The HTML code looks like this: <div class="pslide-container"> <div class="slider slider-horizonta ...

Disable the ability to close the dialog box by clicking

this is my dialog <div *ngIf="visible" class="overlay" (click)="close()"> <div role="dialog" class="overlay-content"> <div class="modal-dialog" (click)="$event.stopPropagation()"> <!-- Modal content--> ...

Steps for showcasing a automated slideshow

I'm currently working on creating a slideshow that automatically displays multiple images. While the first image shows up just fine, it doesn't seem to transition to the next one. var currentSlide = 0; displaySlides(); functio ...

Unable to click on hyperlinks in TinyMCE's read-only mode

I have a situation where I am displaying TinyMCE content inside a modal in read-only mode to show the user the information but not allow them to edit it. The content displays correctly, however, my links are not functioning. When clicked, they do not tri ...

"Executing the ajax send() function does not result in any changes to the

Just starting to explore ajax and I need some help. Can anyone explain why the address bar is not updating when using ajax send()? The connection is working, but it keeps displaying "There is no variable!" PS: Please note that I prefer not to use JQuery. ...

Ways to implement CSS with javascript

I'm using PHP to retrieve data from my database and then leveraging Javascript to enable users to add it. However, I am facing challenges in making a div change its background color and apply borders. <div class="displayedItems"></div> &l ...

Transform Vue.js into static HTML output

Is there a way to convert a Vue.js component into static html without the need for javascript? I am specifically interested in retaining styles. I am searching for a library where I can execute code similar to this: SomeNestedComponent.vue <template> ...

JavaScript - AJAX Call Terminated after a Period on Secure Socket Layer (SSL)

Currently, my AJAX calls over an SSL connection using the Prototype JS framework run smoothly initially. However, after 10 seconds of being live on the page, they start failing with a status of 0 or 'canceled' in the Network Inspector... This is ...

The table is unable to properly display the array data

My code includes an AJAX function that sends a GET request to an API and receives data in the format shown below: { "firstname": "John", "lastname": "Doe", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6 ...

jQuery error message: "Oops! Looks like content.fadeTo isn't a valid function."

When attempting to run my jQuery code, I encountered an error stating 'content.fadeTo is not a function'. Below is the code snippet in question: $.fn.infiniteScroll = function (options) { var observer, filesControl = 0, settings; ...

Troubles with Internet Explorer compatibility when using jQuery Validate plugin and HTML5 Placeholder plugin

I am encountering an error with the Jquery validate and HTML5 placeholder. The functionality works perfectly in Chrome and Firefox, but I am facing issues in IE 9 and below. The problem only occurs after hitting submit for the first time. When I type into ...

Does renaming a sub-directory in the static directory of an IntelliJ Spring Boot project cause any changes?

I'm a newcomer to IntelliJ and I've been using it to develop a Spring Boot application. Right now, my project structure looks like this: My goal is to set up a "css" directory within the "static" directory under the "resources" section so that I ...

Different Div Sizes Based on Device Type (Bootstrap)

I am currently working on a Bootstrap 3 website and have several small divs displayed on the page. I want to adjust their size for desktop view and make them full width for mobile view. Here is my approach: I attempted to place each small div within a co ...

Performing subtraction on two arrays in Javascript

Is there a way to eliminate all duplicate elements from one array list that are also present in another array list using the .filter() method of ES6 javascript? I am open to solutions in jQuery as well, but they must be compatible with IE11+ and Chrome fo ...

Progressively modifying related elements over time intervals

I have a specific list of p elements in my HTML code that I need to modify sequentially with a time interval of 1 second. Here is the HTML: <p>Changing first sentence!</p> <p>Second sentence ready!</p> <p>Third one coming up ...