Joseph Joseph - 1 year ago 87
HTML Question

Change opacity of div background picture

I have a DIV with some text and a background image. I want to reduce the opacity of the background image. But when I apply opacity to the DIV it affects the texts within the DIV. How do I change the opacity of the background image without changing the opacity of the texts in the DIV?

I have this code I got from another question on stackoverflow, which I use to reduce opacity of another div but i dont know how to modify it to achieve the above question.

function convertHex(hex,opacity){
hex = hex.replace('#','');
r = parseInt(hex.substring(0,2), 16);
g = parseInt(hex.substring(2,4), 16);
b = parseInt(hex.substring(4,6), 16);

result = 'rgba('+r+','+g+','+b+','+opacity/100+')';
return result;

$(".add_to_cart_button").click(function() {


Answer Source

First step is add z-index: -1; and position: relative; to your back div css:

Ways to change opacity background:

$("#backDiv").css("opacity", "0.4");
$("#backDiv").css({ opacity: 0.4 });
$("#backDiv").fadeTo("slow", 0.4);
$("#backDiv").fadeTo(1000, 0.4); // fist parameter is animate time in ms

Test button with possibility do some action after the animation:

$("#buttonTest").click(function() {
  $("#backDiv").fadeTo("slow" , 0.4, function() {
    // Animation complete. You can add some action.

I hope it helps...

Good Luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download