L84
L84

Reputation: 46308

Type Error $ is not a function

I am using a jQuery Based Memory Game on my site. It works well overall but I want a "Play Again" Link and stats at the end to show. I cannot get that code to work. I see this error:

TypeError: $ is not a function
  [Break On This Error]     

    var game = $('div.slashc-memory-game'); // get the game

Here is the JS:

    // this script shows how you can get info about the game
    var game = $('div.slashc-memory-game'); // get the game
    var info = $('p#info').find('span'); // get the info box
    var playAgain = $('a#play-again').css('visibility', 'hidden'); // get the play again link
    // format time like hh:mm:ss
    var formatTime = function(s)
    {
        var h = parseInt(s / 3600), m = parseInt((s - h * 3600) / 60); s = s % 60;
        return (h < 10 ? '0' + h : h) + ':' + (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s);
    }
    // listen for game 'done' event 
    game.bind('done', function(e)
    {
        // show basic stats
        var stats = game.slashcMemoryGame('getStats');
        info.html('Success ! Number of clicks : ' + stats.numClicks + ', elapsed time : ' + formatTime(parseInt(stats.time / 1000)) + '.');
        playAgain.css('visibility', 'visible'); // show link
    });
    // play again action
    playAgain.click(function(e)
    {
        playAgain.css('visibility', 'hidden'); // hide link
        info.html('Memory Game, click to reveal images'); // reset text
        game.slashcMemoryGame('restart'); // restart game
        e.preventDefault();
    });

Here is a Fiddle

Upvotes: 4

Views: 23238

Answers (4)

Pevara
Pevara

Reputation: 14310

as fiddle automaticly adds the onload function, your code was actually working fine: http://jsfiddle.net/ZXMUB/5/

All i did was uncomment the first line where the game variable is beeing assigned, and remove closing </script> tag from the js window.

Are you sure on your actual site the code is inside a $(document).ready function (or something similar) and the jQuery library gets loaded properly?

Upvotes: 1

Richard Robertson
Richard Robertson

Reputation: 440

Try replacing $() with jQuery() and see if you continue to get this error. The error indicating that it isn't a function means that either the jQuery file was not loaded yet or the $ name was freed intentionally.

If jQuery() function doesn't work, make sure that you are loading the jQuery file before your script block/file.

Upvotes: 1

Lucas Green
Lucas Green

Reputation: 3959

Your code was missing a document ready handler. Updated:

http://jsfiddle.net/ZXMUB/1/

Upvotes: 0

Chris Carew
Chris Carew

Reputation: 1418

wrap your code in a "ready" function, like so

$(function(){  

 ...

});

Your code is executing before jquery is loaded.

Upvotes: -1

Related Questions