View Full Version : using javascript to float an element!

02-05-2007, 08:02 AM
Can someone help me with this?
Is it possible to change an element that is floating to the left:

float: left;

to an element floating to the right?

I've tried:

funtion changeFloat(){
document.getElementById('links').style.float = 'right';

but that doesn't work!

I want to do this so the viewer can dynamically change the orientation of the page just by clicking a button without having to reload the page.

Thanks in advance!

02-05-2007, 08:55 AM
could try changing class name

funtion changeFloat(){
document.getElementById('links').className = 'rightclassrule';

Bill Posters
02-05-2007, 09:09 AM
You're trying to use getElementById to target an element by its class.

If there's only one instance of the .links class, then the simpler option would be to change it to an id attribute.

<div id="links"></div>

This would now mean that the target element has an id which you can then address using getElementById('links').

Alternatively, if there is more than one instance of class="links", you could actually use something like a custom getElementsByClass function.


function hasClass(obj,cName) {

var cNameRegEx = new RegExp('(^|\\s)' + cName + '(\\s|$)');

return (obj.className && obj.className.match(cNameRegEx));


function getElementsByClassName(cName,trgtTagName,trgtNode) {

/* Requires:
hasClass */

if (!document.getElementsByTagName) return true;

var tName = (trgtTagName) ? trgtTagName : '*';
var tNode = (trgtNode) ? trgtNode : document.getElementsByTagName('body')[0];

var trgtEls = new Array();

var els = tNode.getElementsByTagName(tName);
for (var i = 0, tEl; tEl = els[i]; i++) {
if (libJS.hasClass(tEl,cName)) {
if (trgtEls.push) { trgtEls.push(tEl); }

return trgtEls;



var trgtEls = getElementsByClassName('links');

02-05-2007, 04:59 PM
okay, for one, Bill Posters, you gave me a lot of info that I either already knew, or I didn't need to know. But thank anyways!

vwphillips, thanks! I used className to change the float.. just had to make 2 separate classes for it with one slight difference.. (float:right) and it worked perfectly! I can't beleive I didn't think of that!

Thank you very much!! :thumbsup: