Please show me how to set this style tag with javascript

A

applegreenss

Hi, can someone please show me how to set the following conditions for
this DIV tag?

<div style="position:absolute;left:0px; top:0px;" id="changeme">HELLO
WORLD</div>

I want to be able to change the position to 'relative' and the top
position to negative '-100px' with javascript

Thank you! :))
 
K

KC

I'm new to JavaScript, but I think you can do something like this:

var obj=document.getElementById("changeme");
obj.style.position = 'relative';
obj.style.top = '-100px';


KC
 
Y

Yorian

KC You are exactly right!

But to make things a bit more easy you can put it in a function, like
so:

function changePosition(id,posType,x,y){
var obj = document.getElementById(id);

obj.style.position = posType;
obj.style.left = x;
obj.style.top = y;
}

Now you can use this function everytime you want to do a change like
this bij calling the function: example:

<div onclick="changePosition(this,'absolute', '-100px', '0px')">

this should work as well and might make things a bit more handy.

Yorian
 
C

collintmiller

Great stuff yorian!

extra credit style-setting function for over-achievers:

var myHelpers // Name space your code to avoid embarrassing collisions.
// You might want to pick a more unique namespace.
// com.yourSite is a pretty solid choice
// Don't always have to do this, but if you want others to use your
code, or to
// user others code it's something to think about.

myHelpers.setStyle = function( id, styles )
{
var style,
element = document.getElementById( id )

for ( style in styles ) // for each key in a { key: 'value' }
construct
{
if ( styles.hasOwnProperty( style ) // don't want to go running
up the prototype chain
{
element.style[ style ] = styles[ style ]
}
}
}

Use it like:

myHelpers.setStyle( 'someElement', { color: '#fff', backgroundColor:
'#454545' } )

Happy scripting!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top