HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

JavaScript on page load and on scroll functions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascriptscrollpageloadandfunctions

Problem

Would it serve much purpose to work at refactoring the latter parts of this code?

// This part is OK
function isScrolledIntoView(elem, trigger_height) {

  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();
  var elemTop = elem.offset().top;

  if (trigger_height == false) {
    trigger_height = elem.height()
  }
  var elemBottom = elemTop + trigger_height;

  return ((elemBottom = docViewTop));
}

// This function happens when the page first loads
$("p").addClass('hidden').each(function() {
  $this = $(this);
  if (isScrolledIntoView($this, false)) {
    $this.removeClass("hidden");
  }
});

// This function happens on scroll, but basically repeats itself    
$(window).off('scroll').scroll(function() {
  $("p.hidden").each(function() {
    $this = $(this);
    if (isScrolledIntoView($this, false)) {
      $this.removeClass("hidden")
    }
  });
});


To me, it seems like there isn't – but at the same time its repetitive:

$this = $(this);
if (isScrolledIntoView($this, false)) {
  $this.removeClass("hidden")
}


Is there a general rule that anyone follows such as "only refactor if you're looking at > 5 lines of repeated code", or should you be refactoring absolutely everything as you go?

Solution

I can't really see much to refactor in your code except a few things, so I'll go through those.

if (trigger_height == false)


could be if (!(trigger_height))

$this = $(this);
if (isScrolledIntoView($this, false)) {
    $this.removeClass("hidden");
}


I don't really see why you need to initialise $this, you could just use $(this) later on instead.

Code Snippets

if (trigger_height == false)
$this = $(this);
if (isScrolledIntoView($this, false)) {
    $this.removeClass("hidden");
}

Context

StackExchange Code Review Q#93734, answer score: 2

Revisions (0)

No revisions yet.