Masonry : undefined is not a function

ClmentM picture ClmentM · Jul 23, 2014 · Viewed 9.6k times · Source

I know what the undefined is not a function error means, but I don't get why it is showing up here.

I just downloaded the last Masonry version and tried to follow the docs. (http://desandro.github.io/masonry/docs/methods.html)

The layout is working fine, but it seems like I can't use any masonry() function at all. Always getting the undefined is not a function error on my masonry() calls.

Since the layout is working, I'm assuming the masonry script is working fine, then why can't I use masonry(...) without this undefined function error ?

(I searched about changes from Masonry v2 to Masonry v3, but didn't find anything related to this function)

Partial HTML code :

<a class="navbar-brand" id ="test-masonry" href="#">...</a>

<div id="masonry-container" class="js-masonry" data-masonry-options='{ "columnWidth": 330, "itemSelector": ".item" }'>
    <div class="item">
        <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#createNewBlock">Create a new block</button> 
    </div>
</div>

<!-- Freshly downloaded from the official Masonry website -->
<script src="js/masonry.pkgd.min.js"></script> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/appCtrl.js"></script>

<!--  Copied from the example in the docs -->
<script>
$(function(){
    var $container = $('#masonry-container');
    $('#test-masonry').click(function(){
        var $boxes = $('<div>Test !</div>');
        $container.prepend( $boxes ).masonry( 'reload' );
    });
});
</script>

Answer

Karl-Andr&#233; Gagnon picture Karl-André Gagnon · Jul 23, 2014

You are loading Masonry before jQuery, hence why you are getting undefined. When including masonry, it check if jQuery is loaded. In case it is, it will set the Masonry property to the jQuery object : $.fn.masonry. So when you load Masonry before jQuery, you are not allowed to use jQObject.masonry().

The layout is working fine because Masonry doesnt need jQuery to work