Anderson
Anderson

Reputation: 363

Hidden/show image scrolling

Seeing that effect

$(window).scroll(function() {
  if ($(this).scrollTop() > 0){
    $('.a').fadeOut();
  }
  else {
    $('.a').fadeIn();
  }
});

link: http://jsfiddle.net/MFUw3/239/

how can I start that with my image hidden and show with the scroll?

I'm a beginner.

Upvotes: 2

Views: 10767

Answers (2)

Kolby
Kolby

Reputation: 2865

http://jsfiddle.net/MFUw3/1834/

First set the display to

display: none;

in your css.

Then when you scroll fadeIn.

$(window).scroll(function() {
    $('.a').fadeIn();
});

So to optimize this a little better there's a few things we can do. First, every time you call $(); it's running a function. We can prevent this function from being called every time you scroll by defining a outside the scroll function.

var a = $('.a');
$(window).scroll(function() {
    a.fadeIn();
});

Second, we don't want to run fadeIn() every time we scroll, because after the first time the user scrolls it's going to be visible. What we can do is unbind the scroll event.

var win = $(window);
var a = $('.a');

win.on('scroll', function() {
    a.fadeIn();
    win.off('scroll');
});

http://jsfiddle.net/MFUw3/1835/

Upvotes: 2

matthias_h
matthias_h

Reputation: 11416

By changing to

$(window).scroll(function() {
  if ($(this).scrollTop() > 0) {
    $('.a').fadeIn();
  }
  else {
    $('.a').fadeOut();
  }
});

and setting display:none; to a.

Fiddle

Upvotes: 3

Related Questions