Before answering the question, a note about what was said in the comments: Javascript variable declarations do not need $
up front. As far as I know, this is a form that developers have adopted to make it easier to read the code, distinguishing that variable is a DOM element. In the same way that they use variables with name in box as convention for constants in some languages.
// Você 'bate o olho' e sabe que '$foo' é algum elemento no documento.
$foo.insertAdjacentHTML('afterend', '<p> olá </p>');
In your case, the problem is that you are running a script that depends on jQuery, but when it is executed JQuery has not yet been loaded.
Another problem is that you are entering the value of className
in the function addClass()
. The value has .
before the class name and this is not necessary, jQuery will try to add a class named ..teste-css
and it will never work. addClass
already knows that a class will be inserted, so it is not necessary to point, only the class name ( teste-css
).
Your code looks like this:
<!doctype html>
<html>
<head>
<style>
.teste-css {
color: red;
}
</style>
</head>
<body>
<p>Desça a página</p>
<div id="minhaDiv" class="">
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<h1>Teste2</h1>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function(){
var $document = $(document),
$element = $('#minhaDiv'),
className = 'teste-css';
$document.scroll(function(){
if($(this).scrollTop() >= 5)
$element.addClass(className);
else
$element.removeClass(className);
});
});
</script>
</body>
</html>