...

View Full Version : How to? An element inside a div gains/loses focus, div class gets swapped



jibegod
06-10-2007, 08:11 PM
New to Javascript and I'm trying to accomplish this.. I'm wrapping text input and submit button form elements inside a div. When either the text field or the submit button gain focus, I want to swap the class on the parent div. The form elements themselves wouldn't change, but the wrapper div would, for example, gain and lose a border depending on whether any of its contents had focus.

Any suggestions?

1212jtraceur
06-11-2007, 04:39 PM
You would have a way to identify the parent div (say, an id) and have your event handler change the class:




<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>

<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-style-type" content="text/css" />
<meta http-equiv="content-script-type" content="text/javascript" />

<link href="" rel="stylesheet" type="text/css" /><!-- External Styles -->

<!-- Internal Styles -->
<style type="text/css">
/* <![CDATA[ */
* {
margin : 0 ;
padding : 0 ;
}

#parentDiv {
border : 1px solid black ;
}

#parentDiv.childFocused {
border : 5px solid red ;
}
/* ]]> */
</style>

<script src="" type="text/javascript"></script><!-- External Script -->
<!-- Should be: <link href="" rel="script" type="text/javascript" /> -->

<!-- Internal Script -->
<script type="text/javascript">
/* <![CDATA[ */

/* ]]> */
</script>
</head>

<body>
<script>
function $ ( id ) { return document.getElementById( id ) ; }

function focusHandler()
{
$( 'parentDiv' ).className += ' childFocused' ;
}

function blurHandler()
{
$( 'parentDiv' ).className = $( 'parentDiv' ).className.replace( ' childFocused' , '' ) ;
}

var kids = $( 'form' ).childNodes ;
for ( var i = 0 , max = kids.length , kid ; i < max ; i += 1 )
{
kid = kids[ i ] ;
if ( !kid.addEventListener ) { break ; } // skip this one because the next stuff won't work

kid.addEventListener(
'focus' ,
focusHandler ,
true
) ;
kid.addEventListener(
'blur' ,
blurHandler ,
true
) ;
}
</script>

<div id="parentDiv">
<form id="form" action="">
<input type="text" />
<input type="submit" />
</form>
</div>
</body>
</html>


That doens't seem to work when I try it...but it should give you (or someone else) a starting point.

rnd me
06-11-2007, 05:47 PM
The above code looks a bit overkill.
I tested this in ie6 and ff2:



.

<html><head><style>
.red {background-color:#FF0000}
.blue { background-color:#0000FF}
</style></head><body>

<div class="red" id="parentDiv">
<form id="form" action="">
<input type="text"
onfocus="this.parentNode.className='blue'"
onblur ="this.parentNode.className='red'"
/>
<input type="submit" />
</form>
</div></body></html>

.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum