Set transparency of a DIV and its contents using jQuery
Asked Answered
B

4

22

What is the best way to set the transparency of a HTML DIV element and its contents using jQuery?

Basle answered 20/8, 2009 at 22:59 Comment(1)
Transparency is the same as opacity. Answer is here: https://mcmap.net/q/587587/-setting-opacity-of-html-elements-in-different-browsersCyanine
E
38

$('#my_element').css({ 'opacity' : 0.7 });

Do you want to actually set the opacity to each of the contained elements as well, or you just want it to 'appear' as if the child elements have the same opacity?

As an example to my question, if you wanted something that sets an element, and each of the children elements, you could do something like this

html

<div id="my_element">
  <div>
    lorem
  </div>
  <div>
    ipsum
  </div>
</div>

jquery

$('#my_element').children().
                 css({ 'opacity' : 0.25 }).
                 end().
                 css({ 'opacity' : 0.25 });

Hope this helps. Cheers.

Ellswerth answered 20/8, 2009 at 23:1 Comment(0)
M
10

Another option - Save your keyboard and use fadeTo:

$('#someDiv').fadeTo("slow",0.5);
Menopause answered 20/8, 2009 at 23:30 Comment(0)
D
1

As theIV said you can use the css method, but as an alternative you can use animate:

$('#my_element').animate({ opacity: 0.5 }, 100);

this will animate the opacity of you div (and its contents) to 0.5 (from whatever it was to begin with) in 100 milliseconds.

Duggan answered 20/8, 2009 at 23:7 Comment(0)
B
1

Try this properties

$('#my_div').css("opacity", "0.5"); //Immediately sets opacity $('#my_div').fadeTo(0, 0.5); //Animates the opacity to 50% over the course of 0 milliseconds. Increase the 0 if you want to animate it. $('#my_div').fadeIn(); //Animates the opacity from 0 to 100%

Bevus answered 23/5, 2017 at 4:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.