Robby Bennett Robby Bennett - 2 months ago 6
jQuery Question

jQuery "$.cookie" not a function

I can't figure out why I'm getting this simple error in the console:

Uncaught TypeError: $.cookie is not a function


Here is where I implement JavaScript and jQuery:

<script src="jquery.js"></script>
<script src="cookies.js"></script>
<script src="scripts/changeTheme.js"></script>
<script>
function cookieTest() {
$.cookie("test", "Cookies are working!");
alert($.cookie("test"));
};
cookieTest();
</script>


I checked a thousand times, and I don't see a reference typo. I tried this by viewing my site offline as well as online.

I downloaded the cookies plugin from https://github.com/js-cookie/js-cookie.

Also, alerts work when I do this:

<script src="jquery.js"></script>
<script src="cookies.js"></script>
<script src="scripts/changeTheme.js"></script>
<script>
function cookieTest() {
alert("Test");
};
cookieTest();
</script>


My file is named cookies.js because I simply copied the source code from github and put it in a new js file.
Directory

Answer

The library you're using is not a jquery plugin. Use an older version - https://github.com/carhartl/jquery-cookie/blob/master/src/jquery.cookie.js

As I didn't find any cdn source of this plugin I've copy-pasted it's content and it's working. Example: https://jsfiddle.net/wbcq3ho4/

<script src="CORRECT LIBRARY PATH HERE"></script>
<script>
    function cookieTest() {
        $.cookie("test", "Cookies are working!");
        alert($.cookie("test"));
    };
</script>

<button type="button" onclick="cookieTest();">
Click me
</button>

Just download the file manually or using bower/composer and put the correct link in your html code

Comments