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.
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) {
e.preventDefault()
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.