Javascript experiment

It was kind of hard to pick the first topic, because I couldn’t make up my mind in which category to post. I had to choose between PHP, Ajax and JS. In the end, I decided to post an article about an older experiment which never got used in a project, because it’s really simple to implement, but if it is used in the right circumstances, it can enhance the visual feel of a website.

To put it simply, if you have a <div> element, it would look good if it had a drop shadow, that has a dynamic light source, in this case, the mouse cursor.

You can see it here.

The document structure is really simple, 2 divs:

<body>
<div id=”div2″></div>
<!– the shadow –>
<div id=”div1″></div>
<!– the div which casts the shadow –>
</body>

The CSS part is also very simple. We start out with two styles:

#div1
{
background-color:#00CCFF;
height:175px;
left:100px;
position:absolute;
top:100px;
width:300px;
}

#div2
{
background-color:#000000;
filter:alpha(opacity=25); /*IE opacity*/
height:175px;
left:100px;
opacity:0.25;
position:absolute;
top:100px;
width:300px;
}

Now that we have the element structure and the styles in place, the only thing that remains is to move the “div2″ element accordingly. We can do this using Javascript.

The hardest part is to get the mouse coordinates, since IE handles this issue differently. IE uses the event handler to get the mouse coordinates

We start by doing a browser check:

var IE = document.all?true:false;

The next step is to tell the browser that we need to access the mouse coordinates:

if (!IE) document.captureEvents(Event.MOUSEMOVE)

and we specify the event (mouse movement) function:

document.onmousemove = getMouseXY;

Finally, the function itself:

var tempX = 0; /*mouse X*/
var tempY = 0;
/*mouse Y*/

function getMouseXY(e)
{
	if(IE)
	{
		tempX = event.clientX + document.body.scrollLeft;
		tempY = event.clientY + document.body.scrollTop;
	}
	else
	{
		tempX = e.pageX;
		tempY = e.pageY;
	}  

	if(tempX < 0) //clamp to 0
	{
		tempX = 0;
	}
	if(tempY < 0) //clamp to 0
	{
		tempY = 0;
	}  

	xDrop = 100 + (240 - tempX) / 10;  // dropshadow X coordinate
	yDrop = 100 + (177 - tempY) / 10;  // dropshadow Y coordinate

	document.getElementById('div2').style.top = yDrop + 'px';   //style position update
	document.getElementById('div2').style.left = xDrop + 'px';

	return true;
}
Posted in: Javascript

First post

Hello and welcome to DevTalk!

This is a web development blog, for both general and specific topics and subjects like CSS, HTML, Javascript, PHP, Ajax, MySQL and more. The articles will present details regarding certain web development aspects, both theoretical and practical, as well as a description of that specific issue involved in a project (script, website etc.).

Posted in: Uncategorized