What is the work of this line of code?

Hello, I wondered what is the meaning of the code that I commented
This is smooth scrolling code. You can whole code in CodePen

	$('a[href^="#"]').on('click',function (e) {

	    var target = this.hash,
        // below code
        $target = $(target);
        // above code

	    $('html, body').stop().animate({
	        'scrollTop': $target.offset().top
	    }, 900, 'swing', function () {
	        window.location.hash = target;

It is caching a reference to the target, so that the event functions can have an easy reference to it.

1 Like

Thank you :slight_smile:

Could you expand on that a little Paul? I can see that the code has both the var target and $target in it, but I’m not sure I’m following how the two differ in value/use in this case.

1 Like

Because it’s an animation that’s taking place, you want to minimise the amount of work that the browser is doing each frame.

With just the target it can be costly for jQuery to search for $(target) on every frame of the animation.

To help save on that cost, the search is performed once and saved to a separate variable of $target, which allows you to use a more direct reference to the desired target without needing to search each and every frame.


Actually, the $(target) reference is only used once here to get the offset top and pass it to the .animate() method; jQuery won’t have to search for it again. Nevertheless, assigning it to a dedicated variable certainly makes the code more readable.

Now if you wanted to actually cache it, you might to do so outside the event handler, using the hash as lookup key:

$(document).ready(function () {
  var targets = {}

  $('a[href^="#"]').on('click', function (e) {

    var hash = this.hash
    var $target = targets[hash]

    if (!$target) {
      $target = targets[hash] = $(target)

    $('html, body').stop().animate({
      'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
      window.location.hash = hash

… although this would probably be overkill for such a simple click handler.

target is the the fragment identifier of the clicked anchor element’s href, while $(target) is the element the identifier references.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.