Connecting Tech Pros Worldwide Forums | Help | Site Map

move div tag with javascript

Familiar Sight
 
Join Date: Oct 2007
Location: israel, Tel Aviv
Posts: 130
#1: Sep 3 '08
hello ppl - long time....

i was wondring how i can get the position of a <div> tag,
i want to move it to the left or right on a press of a button

please help
thanks

Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,660
#2: Sep 3 '08

re: move div tag with javascript


You can accomplish that by changing the CSS properties (good candidates are: position, left, right, top, bottom, padding and margin). An element's CSS property is accessible via [element].style.[cssProperty].

regards
Familiar Sight
 
Join Date: Oct 2007
Location: israel, Tel Aviv
Posts: 130
#3: Sep 10 '08

re: move div tag with javascript


thanks man for your fast reply and sorry for my late one :(

still thats not working for me
here is what i done:

file.cs:
Expand|Select|Wrap|Line Numbers
  1. div{
  2.     background:#999999;
  3.     width:200px;
  4.     height:100px;
  5. }
  6. div.test{
  7.     left:100px;
  8. }
javascript function:
Expand|Select|Wrap|Line Numbers
  1. function Find(x){
  2.     //alert(document.getElementById(x).style.position);
  3.     pos = document.getElementById(x).style.position;
  4.     document.getElementById(x).style.position = pos + 150;
  5. }
thats my main page:
[HTML]<body>
<div id="mydiv" class="test">
text.text.text.text.text.text.text<br />
<a href="#" onClick="Find('mydiv');">move</a></div>
</body>[/HTML]

what am i doing wornge here :\
thanks
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,660
#4: Sep 10 '08

re: move div tag with javascript


Quote:

Originally Posted by Amzul

Expand|Select|Wrap|Line Numbers
  1. function Find(x){
  2.     //alert(document.getElementById(x).style.position);
  3.     pos = document.getElementById(x).style.position;
  4.     document.getElementById(x).style.position = pos + 150;
  5. }
what am i doing wornge here :\
thanks

I think you mixed position with (say) left. values for element.style.position are: absolute, relative, static, fixed. you probably meant element.style.left. and you forgot the 'px'.

note: Trying myself (FF 3.01/Mac OS 10.4.11) I had no problems setting the element's style this way, but I could get the settings only through:
Expand|Select|Wrap|Line Numbers
  1. var elem = document.getElementById("_elem_id_");
  2. var cs = window.getComputedStyle(elem, null);
  3. var val = cs.left; // only works for absolute values (i.e. no em, ex, %)
dunno how it is with IE
FF/Opera can also use the methods getPropertyValue() / getPropertyCSSValue() (DOM level 2 - style)

regards
Reply