Hello! Im currently trying to learn javascript and is stuck with a small problem. I want an image to have 50% opacity when mouseout and 100% when mouseover. I first tried this and it works fine. function fadeInAndOut(){ fadeOut(); document.getElementById("bilde").onmouseover=fadeIn; document.getElementById("bilde").onmouseout=fadeOut; function fadeIn(){ document.getElementById("bilde").style.opacity="1"; } function fadeOut(){ document.getElementById("bilde").style.opacity="0.5"; } } Code (markup): But i want it to be cleaner and more versatile so i made one fuction in stead and pass values to it. This is were things dont work. function fadeInAndOut(){ document.getElementById("bilde").onmouseover=fade(1); document.getElementById("bilde").onmouseout=fade(0.5); function fade(opacity){ document.getElementById("bilde").style.opacity=opacity; } } Code (markup): Nothing happens i guess i must be someting wrong whith The passin of values. Any help is higly appreciated
The values on the end of document.getElementById("bilde").style.opacity="0.5"; look to be strings. Have you tried passing them with quotes around them? document.getElementById("bilde").onmouseover=fade("1"); document.getElementById("bilde").onmouseout=fade("0.5");
Thanks for the tip, but i have tried it. Thats what i think is so strange. I have tried asigning the value to a local variable and use that as the value, and that works fine. I dont se the difference from passing in a value. It should still act like a variable. I post all the the code here. Its not much. Im just playing around to learn javascript. Here is the javascript: window.onload = clickhandler; /*function fadeInAndOut(){ fade("0.5"); document.getElementById("bilde").onmouseover=fade("1"); document.getElementById("bilde").onmouseout=fade("0.5"); function fade(opacity){ document.getElementById("bilde").style.opacity=opacity; } } Code (markup): Here is the Html; <div id="bildeskift"> <img id="bilde" src="Bilder/Design/Bilde 004.jpg" name="bilde" width="200" height="200" /> </div> Code (markup): And here is the CSS: #bildeskift { background-image: url(../../Bilder/Design/bakgrunn.jpg); height: 200px; width: 200px; } Code (markup): Thanks for any help
// wrong document.getElementById("bilde").onmouseover=fade("1"); document.getElementById("bilde").onmouseout=fade("0.5"); // right document.getElementById("bilde").onmouseover=function() { fade(1); }; document.getElementById("bilde").onmouseout=function() { fade(0.5); } Code (javascript): if you need to pass arguments then you need to wrap it into an anonymous function (or a named one, does not matter).