views:

31

answers:

4

I'm using the following code to control a div with the ID 'sidebar'

var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
            $(window).scroll(function (event) {
                // what the y position of the scroll is
                var y = $(this).scrollTop();

                // whether that's below the form
                if (y >= top) {
                  // if so, ad the fixed class
                  $('#sidebar').addClass('fixed');
                } else {
                  // otherwise remove it
                  $('#sidebar').removeClass('fixed');
                }
              });

However when a page that odes not contain div#sidebar it throws out an error stating #sidebar is null (because it's not there!)

How can I convert this code to only happen IF there is div#sidebar on the page?

+1  A: 
if($('#sidebar').length > 0)
{
 //your code here
}
Brandon Boone
+1  A: 

If I am not wrong you can use

if ($('#sidebar').length > 0){

   .............

}

to achieve that.

MSI
Thanks guys - worked a treat!
Jonny Wood
A: 

You can try this.

if($('#sidebar').size > 0){

//your code

}
TALLBOY
`.size()` is a method...which really just calls `.length` :)
Nick Craver
+2  A: 

You can reduce your code down using .length to check if it exists and cache the selector, like this:

var sb = $('#sidebar');
if(sb.length) {
  var top = sb.offset().top - parseFloat(sb.css('marginTop').replace(/auto/, 0));
  $(window).scroll(function () {
    sb.toggleClass('fixed', $(this).scrollTop() >= top);
  });
}​

.length returns the number of elements the selector found, if it's not there it'll be 0 or false for the purposes of our if() check. After that we're using .toggleClass(class, bool) to more tersely add or remove the class based on the scroll positon.

Nick Craver