10

I'm trying to add a bit of jQuery code to all elements that have position:fixed set on them. Is this sort of thing possible? It would be very helpful if there is, so I don't have to go through all my code and an extra class to the objects that are fixed.

Brian Leishman
  • 8,155
  • 11
  • 57
  • 93

3 Answers3

24

This one should cover all cases:

$('*').filter(function() {
    return $(this).css("position") === 'fixed';
});

Not as fast as qwertymk's answer, but also work if the css property is inherited from another rule, as demonstrated here.

mgibsonbr
  • 21,755
  • 7
  • 70
  • 112
4

Faster and safer than Colin's answer:

$('*').filter(function(){ return this.style && this.style.position === 'fixed'; });

More about jQuery filter()

Stphane
  • 3,368
  • 5
  • 32
  • 47
qwertymk
  • 34,200
  • 28
  • 121
  • 184
  • 3
    just curious to know what is returned when `this.style` and `this.style.position==='fixed' ` are written seperately ? – HalfWebDev Feb 13 '12 at 11:11
  • 4
    @MegaRacer it's a protective check, if `this.style` is `undefined` `this.style.position` will throw an error `Cannot read property position of undefined` since the compiler checks left to right, if `this.style === undefined` it will fail the expression before the `&&` not causing an error. – Dave Mackintosh May 08 '16 at 09:54
1

If you are only checking for display: none and other display properties. You could use the CSS selector :visible in your usual jQuery selections, like this:

$('.items:visible')

Or to select the hidden elements:

$('.items:hidden')
David Lopez
  • 305
  • 3
  • 6