aHunter
aHunter

Reputation: 3530

Using javascript to display text on top of an image on mouse over

I am new to javascript and would like to have an image that is fully displayed but when you mouse over the image text appears over the top in a div tag and fades the image in the background.

This is my attempt however poor and it is not working.

<style>
/*CSS Style sheet*/
div.image_box_text {
opacity:0;
margin-top:-25px;
background-color:#FFF;
}
</style>

<script>

function fadeImg(obj) {

    obj.style.opacity=0.5;
    obj.filters.alpha.opacity=50;
}

function viewObj(obj1, obj2) {

   fadeImg(obj1);
   obj2.style.opacity=1;
   bj2.filters.alpha.opacity=100;
}

</script>

<div>
    <img id='img1' src="../images/index/square/posingS.jpg" onmouseover='viewImg(this, txt1)'/>

    <div id='txt1' class='image_box_text' >This is image box one</div>
</div>

Thanks in advance.

Upvotes: 0

Views: 2411

Answers (1)

Erik Hinton
Erik Hinton

Reputation: 1946


This should get you started.

<style>
/*CSS Style sheet*/
div.image_box_text {
opacity:0;
margin-top:-25px;
background-color:#FFF;
}
</style>

<script>

function fadeImg(obj) {
    obj.style.opacity=0.5;
}

function viewObj(obj1, obj2_name) {
   var obj2 = document.getElementById(obj2_name);
   fadeImg(obj1);
   obj2.style.opacity=1;
}

</script>

First, you cannot simply call an object by an id as you did in viewObj. You must do a document.getElementById on its id. Next you will have to check if filters exists (it only does in IE). A better way to do this is to make .faded and .hidden classes in your stylesheet and have the hover event trigger the adding and removal of them.

Here's this code in action: http://jsfiddle.net/WpMGd/

Upvotes: 2

Related Questions