Xan
Xan

Reputation: 45

Change CSS background from JS/jQuery

.u-section-1 {
  background-image: linear-gradient(0deg, rgba(0,0,0,0.2), rgba(0,0,0,0.2)), url("images/curtains/curtains_header.jpg");
  background-position: 50% 50%;
}

I'm having this class in .css and this jquery. I'm not able to change the background image.

$('.u-section-1').css("background-image", "linear-gradient(0deg, rgba(0,0,0,0.2), rgba(0,0,0,0.2)), url('images/xabbb-min.jpg')");  

The HTML is something like that:

  <section class="u-align-center u-clearfix u-image u-shading u-section-1" id="carousel_4db0">

I also tried with 'document.getElementById or ElementsByClassName. The JS file is running but the change doesn't occur.

Thank you in advance for trying to help me.

Upvotes: 0

Views: 76

Answers (1)

Onkar
Onkar

Reputation: 2594

Nothing wrong with the code, I have replaced the images with CDN link and add button to change the background-image, and it works well

$(function(){
 $(document).on('click','.bgChange', function(){
 $('.u-section-1').css("background-image", "linear-gradient(0deg, rgba(0,0,0,0.2), rgba(0,0,0,0.2)), url('https://picsum.photos/seed/picsum/200/300')");
 });
});
.u-section-1 {
  background-image: linear-gradient(0deg, rgba(0,0,0,0.2), rgba(0,0,0,0.2)), url("https://picsum.photos/id/237/200/300");
  background-position: 50% 50%;
  height:200px;
  background-size:contains;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="u-align-center u-clearfix u-image u-shading u-section-1" id="carousel_4db0"><br/>
<button class="bgChange" stype="button">Change BG</button>

Upvotes: 2

Related Questions