[javascript] change image opacity using javascript

how can I change image opacity using javascript? I'm going to create a fading effect using javascript, is there any sample? is there anything like image.opacity that can be changed through JS code? how is it set?

thanks

This question is related to javascript

The answer is


You could use jQuery's animate or fadeTo.


In fact, you need to use CSS.

document.getElementById("myDivId").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");

It works on FireFox, Chrome and IE.


First set the opacity explicitly in your HTML thus:

<div id="box" style="height:150px; width:150px; background-color:orange; margin:25px; opacity:1"></div>

otherwise it is 0 or null

this is then in my .js file

document.getElementById("fadeButton90").addEventListener("click", function(){
document.getElementById("box").style.opacity  =   document.getElementById("box").style.opacity*0.90; });

You can use CSS to set the opacity, and than use javascript to apply the styles to a certain element in the DOM.

.opClass {
    opacity:0.4;
    filter:alpha(opacity=40); /* For IE8 and earlier */
}

Than use (for example) jQuery to change the style:

$('#element_id').addClass('opClass');

Or with plain javascript, like this:

document.getElementById("element_id").className = "opClass";

I'm not sure if you can do this in every browser but you can set the css property of the specified img.
Try to work with jQuery which allows you to make css changes much faster and efficiently.
in jQuery you will have the options of using .animate(),.fadeTo(),.fadeIn(),.hide("slow"),.show("slow") for example.
I mean this CSS snippet should do the work for you:

img
{
opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
}

Also check out this website where everything further is explained:
http://www.w3schools.com/css/css_image_transparency.asp


You could use Jquery indeed or plain good old javascript:

var opacityPercent=30;
document.getElementById("id").style.cssText="opacity:0."+opacityPercent+"; filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity="+opacityPercent+");";

You put this in a function that you call on a setTimeout until the desired opacity is reached