$block = $('#menu');
Variables must be declared via var
so that they do not become global:
var $block = $('#menu');
$blockPosition = $block.offset().top;
When writing jQuery code, the names of variables containing jQuery sets are usually started with a dollar sign, so just
var blockPosition = $block.offset().top;
if ($windowPosition > $blockPosition) { $block.addClass('fix'); }else{ $block.removeClass('fix'); }
There is a wonderful second parameter to the toggleClass function, only it must be boolean:
$block.toggleClass('fix', $windowPosition > $blockPosition);
$windowPosition
Variables used once can often not be set:
$block.toggleClass('fix', $window.scrollTop() > $blockPosition);
$ window
This variable has never been declared anywhere ...
Tell me please, if $ (window) is used in the code more than once, does it need to be cached in a variable and be the jQuery set window?
You should do the same with all other variables.
In general, my opinion is that if something is requested once during the processing of an event , then there is no need to cache it. This allows you to get the actual elements, avoid cluttering the code with unnecessary variables and potentially holding unused dom elements in memory. In addition, some events may not occur, and with the initial caching we do a lot of unnecessary searches.
But there is another opinion - to immediately cache everything you need.
}else{
It is customary to put spaces around brackets.
} else {
Summary Code:
$(function () { var $block = $('#menu'); var blockPosition = $block.offset().top; $(window).scroll(function () { $block.toggleClass('fix', $(window).scrollTop() > blockPosition); }); });
Although, to be honest, I have doubts about getting the position of the block immediately after loading the document. Should it be exactly there?
var
in front of$block
,$blockPosition
and$windowPosition
to make them local variables - Igor$
in the names of all variables, but it is usually expected that such a variable will contain some special object (jquery, zepto ...),$blockPosition
and$windowPosition
contain the usualint
. - Arnial$
in the beginning is fundamentally wrong.$
does not affect the globality of a variable in any way, nor does it affect anything at all. I apologize for misleading my comment. - Vitaly Emelyantsev