39

I want to check if an element is visible and if yes, I want to scroll down to it. I am trying to achieve that with the following jquery:

var j = jQuery.noConflict();

  jQuery(document).ready(function($) {
    if(j('#element').css('display') == 'block'){
        j('body').scrollTo('#target');
      };
});

but it does not work.

user2539007
  • 393
  • 1
  • 3
  • 4

3 Answers3

13
// jQuery no conflict mode
var j = $.noConflict();

// retain meaning of jQuery's handle (optional but makes it
// sometimes easier if you don't use one-letter assignments
// of jQuery)
(function($){

  // document read
  $(function(){
    // if element is visible (a visible #element was found)
    if $('#element:visible').size() > 0){
      // scroll to #target
      $('body').scrollTo('#target');
    }
  });

})(j);

:visible makes it easier. You're can't just test against display=='block', you'd also have to test for inline-block and others in addition to checking the visibility setting. For example, the element could have display:block:visibility:hidden which doesn't make it :visible.

Brad Christie
  • 96,086
  • 15
  • 143
  • 191
10

Try:

if($(element).is(":visible"))

Refer to this post: How do I check if an element is hidden in jQuery?

Community
  • 1
  • 1
Eirinn
  • 746
  • 8
  • 22
3

Use .is() and :visible

var j = jQuery.noConflict();

jQuery(function($) {
    if($('#element').is(':visible')){
        $('body').scrollTo('#target');
    };
});
Arun P Johny
  • 365,836
  • 60
  • 503
  • 504