Steggie Steggie - 1 year ago 40
CSS Question

Script not working (but works fine on other site)

Ok this is probably a dumb question but, I'll ask. I'm trying to make a div stick when you pass a point on the page while scrolling. I have this script:

<script type="text/javascript">
$(document).ready(function() {
var s = $("#sticker");
var pos = s.position();
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
if (windowpos >= pos.top + 335) {
s.addClass("stick");
} else {
s.removeClass("stick");
}
});
});
</script>


Which works fine on one of my site. But now I'm trying it on a new site. And every time I get an error in my console log saying:
TypeError: $ is not a function
And when I look at the error in my code it highlights the
$(document).ready(function() {
part.

If I remove the
$(document).ready
part and the
});
it tells me the
var s = $("#sticker");
part is
$ is not a function
.

I have tried

<script type="text/javascript">
jQuery(document).ready(function() {
var s = $("#sticker");
var pos = s.position();
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
if (windowpos >= pos.top + 335) {
s.addClass("stick");
} else {
s.removeClass("stick");
}
});
});
</script>


Then it skips the
(document).ready
part, but it again tells me my
var
part is not a function.

If I remove the script I don't have any console log messages. What could be the problem? I tried putting the code in the
header
and
footer
and even just before the
<div id="sticker">...</div>
. Nothing seems to work. The script works perfectly on an other site...

Answer Source

You are running jQuery in noConfilct mode. Which mean, jQuery is only available by jQuery, not over $. You can wrap your code with an ready state or an IIFE to get access to jQuery by $.

Ready State:

jQuery(document).ready(function($) {
    // access jQuery by '$' inside
});

// this is a shorthand for the above '.ready' creation
jQuery(function($) {
    // access jQuery by '$' inside
});

IIFE:

(function($) {
    // access jQuery by '$' inside
})(jQuery);