E. Shio E. Shio - 4 months ago 25
HTML Question

Javascript Optimization

I can't seem to figure out how to get this

JS
to work. The
scroll
function
works but not the hide. Also is there anyway to do this with less lines of code? I want
.down-arrow
to
fade out
after
50px
and hide after the
50px
that way it can't be clicked on. It was working on my site and codepen, but then it randomly stopped working. The code is clearly wrong, but somehow it was working...

JS:

$(window).scroll(function() {
$(".down-arrow").css("opacity", 1 -
$(window).scrollTop() / 50 );
});

$(window).scroll(function() {
$(".down-arrow").hide(fast);
$(window).scrollTop() > 50 );
});


[Edit]

Here is the new JS I wrote with advice on the obvious syntax error and suggestions to place it all in one body, which I was hoping to do anyways:

$(window).scroll(function() {
$(".down-arrow").hide("fast");
$(".down-arrow").css("opacity", 1 -
$(window).scrollTop() / 50 );
});


But now I want the arrow to show when the use goes back up to the top, above the 50px mark.

Answer

First of's first, there is no need to register a funcition twice

var element =  $(".down-arrow");
$(window).scroll(function() {
  if( $(window).scrollTop() > 50){
    if($(element).is(":visible")){
      element.hide("fast"); 
    }
   }else{
    if(!$(element).is(":visible")){
      element.show("fast"); 
    }
    element.css("opacity", 1 -$(window).scrollTop() / 50 );
   }
});