Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have this code, but I not the best to javascript/jQuery so are there any out there who can optimize this code?

$(function(){
    var pos = $("header").offset().top;

    $(document).scroll(function(){
        if($(this).scrollTop() - 10 > pos)
        {   
           $('header').addClass("filled");
        } else {
           $('header').removeClass("filled");           
        }
    });
});
share|improve this question

I would write this like:

$(function(){

  var header = $('header');
  var threshold = header.offset().top;

  $(document).scroll(function(){
      header.toggleClass('filled', $(this).scrollTop() - 10 > threshold);
  });

}

In this version you avoid the "duplicate selector" and have a more clean if statement.

share|improve this answer
    
that was a much better way :o – TheCrazyProfessor 1 hour ago
    
but for reason if I use toggleClass it can't find out what to do, so the class keep toggle on and off – TheCrazyProfessor 1 hour ago
    
@TheCrazyProfessor, I've updated my answer, could you please check new version? – Dan 1 hour ago
    
Amazing! now it works – TheCrazyProfessor 1 hour ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.