fidel fidel - 2 years ago 185
jQuery Question

How to make a background image transparent with JavaScript

Is it possible to change a background image to be transparent when user uploads image? If yes, can you guide me?

Answer Source

Your question leaves out a lot of details that might be pertinent to the question, so I'm going to make some assumptions for the sake of simplicity:

  1. The method by which the user uploads an image is immaterial to the transparent background.
  2. The method by which you get a reference to the element in question is immaterial to the question.
  3. The original background is a solid color.
  4. You don't need to set multiple backgrounds on the same element, but instead want a different element to show through the transparent background.
  5. Transparent here means partially transparent: which is to say that you can still see the original background to some extent, but can also see whatever is underneath it.

In general, you can set an element's background transparent in JavaScript by adjusting its background-color style property to an RGBA (red-green-blue + alpha channel) color. You do that like so: = "rgba(rValue, gValue, bValue, aValue)";

In that snippet, the color is defined by its RGB value split into three integers, each of which is between 0 and 255. So for black (hex value #000000) you'd set it to 0 red (rValue), 0 green (gValue), and 0 blue (bValue); you then set the alpha transparency (aValue) to a number between 1 (fully opaque) and 0 (fully transparent). So if you wanted, say, 30% transparency: you'd set it to 0.30. Putting that all together, you can get black at 30% transparency with: = "rgba(0, 0, 0, 0.30)";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download