0

I have a background-image in my carousel, and i'm trying to add a gradient to it using jQuery.

Here is the CCS code of the element i'm trying to edit:

element.style {
padding: 5% 5%;
margin: 0px 0%;
background-image: url(myImgUrl);
background-position: left top;
background-size: contain;
min-height: 427px;
}

This is how it should like in the end (after adding gradient)

background-image: linear-gradient(to bottom, rgba(0,0,0,0) 20%, rgba(0,0,0,1))+ url(myImgUrl) 

Here is what I tried

      jQuery(function(){
          jQuery(".sa_hover_container").each(function){
                    var img = (this).css("background-image");
                    var newBackground = "linear-gradient(to bottom, rgba(0,0,0,0) 20%, rgba(0,0,0,1)), "+ img ;
                    (this).css(background-image,newBackground);
          });
       });

Is it even possible to do? if so, what am I doing wrong ?

Thanks!

Yoni hodeffi
  • 103
  • 2
  • 8

2 Answers2

0

You can try in this way:

jQuery(function(){

    jQuery(".sa_hover_container").each(function){

        var imgStyle = this.currentStyle || window.getComputedStyle(this, false),
        var bgImage = imgStyle.backgroundImage.slice(4,-1);
        var newBackground = "linear-gradient(to bottom, rgba(0,0,0,0) 20%, rgba(0,0,0,1)), " + bgImage;

        jQuery(this).css(background-image,newBackground);

    });

});

In this way you can get the url of background even if defined inside a CSS file.

Fab
  • 4,526
  • 2
  • 21
  • 45
0

In first fix your JS code

jQuery(function(){
    jQuery(".sa_hover_container").each(function() {
        var img = jQuery(this).css("background-image");
        var newBackground = "linear-gradient(to bottom, rgba(0,0,0,0) 20%, rgba(0,0,0,1)), "+ img;
        jQuery(this).css("background-image",newBackground);
    });
});
step
  • 2,254
  • 2
  • 23
  • 45
  • I'm a bit of a newbie still, that totally fixed it. ty dear sir. – Yoni hodeffi May 30 '18 at 13:48
  • (this) -> jQuery(this), some wrong brackets, background-image -> "background-image". When you will use some good IDE like PHPStorm it will show you what is wrong. – step May 30 '18 at 14:15