views:

171

answers:

4

Hi

Effectively what I need to do in JS is move all absolutely positioned elements down by x pixels. Do I need to loop through every element and try to figure out if it's positioned absolutely? Or is there a better way?

Thanks, Mala

Update: specific: I am using a bookmarklet to inject JS onto any page - thus I cannot change the markup or actual css files in any way. This bookmarklet should, among other things, move all absolutely positioned elements 155 pixels down.

A: 

There is the CSS statement position: fixed - that might do what you want...

nickf
what about ie6 ;)
redsquare
+2  A: 

You could tag all absolutely positioned elements with a specific class name and use the getElementsByClassName in most browsers. Other than that, looping is the only option.

Josef
+1  A: 

phoenix's solution un JQuery-ifed:

var nodes = document.getElementsByTagName("*");
node.foreach(function(n){ // can use foreach since this is FF only
    if(n.style.position=="absolute"){
        n.style.top += parseInt(n.style.top || 0, 10) +"px";
    }
}
mwilcox
+2  A: 

Something like this should do it:

function getStyle(el, prop) {
  var doc = el.ownerDocument, view = doc.defaultView;
  if (view && view.getComputedStyle) {
    return view.getComputedStyle(el, '')[prop];
  }
  return el.currentStyle[prop];
}
var all = document.getElementsByTagName('*'), i = all.length;
while (i--) {
  var topOffset = parseInt(all[i].style.top, 10);
  if (getStyle(all[i], 'position') === 'absolute') {
    all[i].style.top = isNaN(topOffset) ? '155px' : (topOffset + 155) + 'px';
  }
}
kangax
This worked, thanks! I just had to change the topOffset to use getSyle to get the top value, as style.top wasn't returning anything on the page I was testing it on (google search results)
Mala
@Mala Ah yes, good thinking! : )
kangax