1

I'm trying to add a css gradient overlay to an image via javascript. But it's not working. What am I doing wrong?

This code will only show the background image, but not the gradient.

$(document).ready(function() {
   $('html').css('background', 'url(images/image.jpg) no-repeat center center');
   $('html').css('background-size', 'cover');
   $('html').css('height', '100%');

   $('html:before').css('content', '');
   $('html:before').css('height', '100%');
   $('html:before').css('width', '100%');
   $('html:before').css('position', 'absolute');
   $('html:before').css('z-index', '-1');
   $('html:before').css('top', '0');
   $('html:before').css('left', '0');
   $('html:before').css('background', '-webkit-radial-gradient(center, ellipse cover,  rgba(0,0,0,0.07) 0%,rgba(3,3,3,0.07) 1%,rgba(68,68,68,0.25) 20%,rgba(63,63,63,1) 100%);');
}); 

This css works, but I need to do this with javascript.

html{
height: 100%;
background: url("../images/image.jpg") no-repeat center center;
background-size: cover;
}

html:before {
content: " ";
width: 100%;
height: 100%;
position: absolute;
z-index: -1;
top: 0;
left: 0;


background: -webkit-radial-gradient(center, ellipse cover,  rgba(0,0,0,0.07) 0%,rgba(3,3,3,0.07) 1%,rgba(68,68,68,0.25) 20%,rgba(63,63,63,1) 100%); 

}
brewpixels
  • 311
  • 1
  • 5
  • 19
  • Please, use the standard version of css properties instead of vendor prefixed like -webkit. – AlfonsoML May 08 '16 at 17:23
  • 3
    You can't target pseudo-elements in jquery selectors... See for example [Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery](http://stackoverflow.com/questions/5041494/selecting-and-manipulating-css-pseudo-elements-such-as-before-and-after-usin) – CupawnTae May 08 '16 at 17:25
  • Best thing you can do is add/remove css classes, so the styles will remain in the stylesheet file. – Enrico May 08 '16 at 21:07

1 Answers1

0

I believe the best way to do what you are trying is by creating a html canvas. This has been done quite nicely using pimvdb's answer:

(Image gradient on HTML5 canvas)

Hope this helps.

analytical_prat
  • 842
  • 12
  • 14