0

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?

Mr Jonny Wood
  • 3,806
  • 5
  • 30
  • 42
  • Not really direct to the question, but you can replace the entire scroll content with this: `$('#sidebar').toggleClass('fixed', $(this).scrollTop() >= top);` :) – Nick Craver Aug 19 '10 at 23:45
  • @Nick Thanks! Always nice to clean up code. This was actually from a tutorial I found here: http://jqueryfordesigners.com/fixed-floating-elements/ – Mr Jonny Wood Aug 19 '10 at 23:52

4 Answers4

2
if($('#sidebar').length > 0)
{
 //your code here
}
Brandon Boone
  • 16,281
  • 4
  • 73
  • 100
2

If I am not wrong you can use

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

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

}

to achieve that.

MSI
  • 1,124
  • 8
  • 23
2

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
  • 623,446
  • 136
  • 1,297
  • 1,155
0

You can try this.

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

//your code

}
TALLBOY
  • 1,079
  • 1
  • 10
  • 13