Archive for the ‘Pie’ Category

Use JavaScript to Find the Center of the Browser.

Sep 13, 2007

I found myself in a situation where I needed to dynamically display a div in the center of browser’s window without knowing anything about the page or where the user was on it. For example, the user could be at the top of a page or could have scrolled 3000 pixels down. I also wasn’t allowed to use mouse clicks or anything to determine where the users was.

So, to use JavaScript to find the center of the browser’s window regardless of where the user is:

posY = getScreenCenterY();
posX = getScreenCenterX();

dv = document.createElement('div');
dv.setAttribute('id',"css_dialog");
dv.style.cssText = "position:absolute;top:"+posY+"px;left:"+posX+"px;";

function getScreenCenterY() {
var y = 0;

y = getScrollOffset()+(getInnerHeight()/2);

return(y);
}

function getScreenCenterX() {
return(document.body.clientWidth/2);
}

function getInnerHeight() {
var y;
if (self.innerHeight) // all except Explorer
{
y = self.innerHeight;
}
else if (document.documentElement &&
document.documentElement.clientHeight)
// Explorer 6 Strict Mode
{
y = document.documentElement.clientHeight;
}
else if (document.body) // other Explorers
{
y = document.body.clientHeight;
}
return(y);
}

function getScrollOffset() {
var y;
if (self.pageYOffset) // all except Explorer
{
y = self.pageYOffset;
}
else if (document.documentElement &&
document.documentElement.scrollTop)
// Explorer 6 Strict
{
y = document.documentElement.scrollTop;
}
else if (document.body) // all other Explorers
{
y = document.body.scrollTop;
}
return(y);
}

Many thanks to Quirksmode for this page: www.quirksmode.org/viewport/compatibility.html

Count characters in a textarea.

Aug 16, 2007

You just need the bolded text…

<html>
<HEAD>

<script type=”text/javascript”>
function textCounter(textarea, counterID, maxLen) {
cnt = document.getElementById(counterID);
if (textarea.value.length > maxLen)
{
textarea.value = textarea.value.substring(0,maxLen);
}
cnt.innerHTML = maxLen – textarea.value.length;
}
</script>

</HEAD>
<body>
<center>
<form action=”whatever.php”>

<textarea name=”text_area” cols=”50″ rows=”5″ onKeyUp=”textCounter(this,’count_display’,3500);” >
onBlur=”textCounter(this,’count_display’,3500);” >
</textarea>
<br>

<span id=”count_display”>3500</SPAN> characters remaining

<input type=”submit” value=”Submit”>
</form>
</center>
</body>
</html>