• Stars
    star
    235
  • Rank 165,024 (Top 4 %)
  • Language
    HTML
  • License
    MIT License
  • Created over 11 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JQuery Masonry plugin ready for use with Rails asset pipeline

Masonry for Rails asset pipeline

masonry at github

Using fork from masonry

See more Masonry info at masonry README

Versions: Currently uses jQuery Masonry v2.1.08 and Isotope 1.5.25

Please notify if you have any problems ;)

This gem includes:

  • jquery masonry
  • jquery imagesLoaded
  • jquery infinitescroll
  • jquery event drag

For random content generation

  • box maker
  • loremimages

Latest masonry 4.2.0

  • masonry.min

layouts (in masonry/layouts folder)

  • layout/horizontal

Isotope

Isotope is also included. Isotope is very similar to Masonry and might be a nice alternative for some use cases. Why it is included ;)

Isotope assets

all found in the isotope folder

Javascript

  • jquery.isotope.js
  • jquery.isotope.min.js

Extras:

  • jquery.debounced_resize.min.js
  • jquery.throttled_resize.min.js

For latest isotope 2.0

  • isotope
  • layout-mode
  • item

layouts (in isotope/layouts folder)

  • layout/cells-by-column
  • layout/cells-by-row
  • layout/fit-columns
  • layout/horizontal
  • layout/packery

Stylesheets

  • isotope.css

More isotope related stylesheets in isotope folder in `vendor/assets. Use as inspiration...

Please see Isotope License for commercial use.

Usage: See Getting started

Usage

In Gemfile

gem 'masonry-rails'

CSS

You can include stylesheets extracted from the masonry examples directly:

Manifest application.css file:

*= require 'masonry/basic'
*= require 'masonry/centered'
*= require 'masonry/fluid'
*= require 'masonry/gutters'
*= require 'masonry/infinitescroll'
*= require 'masonry/right-to-left'
*= require 'masonry/transitions'

Use these stylesheets as a base in order to play around with different effects... :)

Javascript

masonry

//= require masonry/jquery.masonry

To use latest masonry 4.2.2 without jQuery

//= require masonry/masonry

or the minify version

//= require masonry/masonry.min

Optional

//= require masonry/jquery.event-drag
//= require masonry/jquery.imagesloaded.min
//= require masonry/jquery.infinitescroll.min
//= require masonry/modernizr-transitions

Content generation helpers:

//= require masonry/box-maker
//= require masonry/jquery.loremimages.min

See examples on masonry or github

isotope

All isotope scripts are in the isotope folder

//= require isotope/jquery.isotope

Setup

We will use the infinite scroll example for a full walkthrough of how to setup and use Masonry. We add the classes transitions-enabledand infinite-scroll to the container in order to enable these two effects simultaneously. Look further down in this guide to see configurations of other effects that can be combined ;)

Main container

<div id="masonry-container" class="transitions-enabled infinite-scroll clearfix">

  <div class="box col3">
    ...
  </div>

  <div class="box col1">
    <p>Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. </p>
  </div>

  <div class="box col2">
    <p>
      <a href="http://www.flickr.com/photos/nemoorange/3319714470/" title="Whitlow's on Wilson by nemoorange, on Flickr"><img src="http://farm4.static.flickr.com/3008/3319714470_c05a5cb5a8_m.jpg" alt="Whitlow's on Wilson" /></a>
    </p>
  </div>
  ...
</div>

Note: We use the ID masonry-container in order to ensure against conflicts with other "plugins". Twitter Bootstrap, for example, reserves the class names container and container-fluid for particular (container) layouts.

#masonry-container {
  background: #FFF;
  padding: 5px;
  margin-bottom: 20px;
  border-radius: 5px;
  clear: both;
  -webkit-border-radius: 5px;
     -moz-border-radius: 5px;
          border-radius: 5px;
}

.clearfix:before, .clearfix:after { content: ""; display: table; }
.clearfix:after { clear: both; }
.clearfix { zoom: 1; }

Configuring the different brick sizes:

.col1 { width: 80px; }
.col2 { width: 180px; }
.col3 { width: 280px; }
.col4 { width: 380px; }
.col5 { width: 480px; }

.col1 img { max-width: 80px; }
.col2 img { max-width: 180px; }
.col3 img { max-width: 280px; }
.col4 img { max-width: 380px; }
.col5 img { max-width: 480px; }

Gutters

The gutterWidth option adds additional spacing between columns, but not on the outer sides of the container.

Example:

$(function(){

  $('#masonry-container').masonry({
    itemSelector: '.box',
    columnWidth: 100,
    gutterWidth: 40
  });

});

Add class has-gutters to container for this effect.

Right to left

Enable right-to-left layout by setting the isRTL option to true.

See masonry/right-to-left.css

$(function(){

  $('#masonry-container').masonry({
    itemSelector: '.box',
    columnWidth: 100,
    isAnimated: !Modernizr.csstransitions,
    isRTL: true
  });

});

Add class rtl to container for this effect ;)

Centered

This layout is centered by setting isFitWidth: true and adding necessary CSS position styles margin: 0 auto;.

See masonry/centered.css

.centered { margin: 0 auto; }
<div id="masonry-container" class="transitions-enabled centered clearfix masonry">
  ...
</div>
$(function(){
  $('#masonry-container').masonry({
    itemSelector: '.box',
    columnWidth: 200,
    isAnimated: !Modernizr.csstransitions,
    isFitWidth: true
  });

});

Fluid

For fluid or responsive layouts, where the width of the column is a percentage of the container's width, you can pass in a function for columnWidth.

$('#masonry-container').masonry({
  itemSelector: '.box',
  // set columnWidth a fraction of the container width
  columnWidth: function( containerWidth ) {
    return containerWidth / 5;
  }
});

Use masonry/fluid.css for a head start!

Animated transitions

Transitions used in examples

Note: use masonry/transitions.css for a head start!

Notice the class names: .transitions-enabled, masonry and .masonry-brick.

.transitions-enabled.masonry,
.transitions-enabled.masonry .masonry-brick {
  -webkit-transition-duration: 0.7s;
     -moz-transition-duration: 0.7s;
      -ms-transition-duration: 0.7s;
       -o-transition-duration: 0.7s;
          transition-duration: 0.7s;
}

.transitions-enabled.masonry {
  -webkit-transition-property: height, width;
     -moz-transition-property: height, width;
      -ms-transition-property: height, width;
       -o-transition-property: height, width;
          transition-property: height, width;
}

.transitions-enabled.masonry  .masonry-brick {
  -webkit-transition-property: left, right, top;
     -moz-transition-property: left, right, top;
      -ms-transition-property: left, right, top;
       -o-transition-property: left, right, top;
          transition-property: left, right, top;
}


/* disable transitions on container */
.transitions-enabled.infinite-scroll.masonry {
  -webkit-transition-property: none;
     -moz-transition-property: none;
      -ms-transition-property: none;
       -o-transition-property: none;
          transition-property: none;
}

Note: You can use compass and sass to auto-generate these transitions for all browser prefixes ;)

CSS transitions

Alternatively, you can rely on CSS3 transitions to animate layout rearrangements. Enabling transitions is recommended, as they provide for better browser performance over jQuery animation.

In your CSS, add transition styles below. The Masonry plugin will add a class of masonry to the container after the first arrangement so transitions can be applied afterward. Item elements will have a class of masonry-brick added.

Animate via Modernizr

To get the best of both worlds, you can use Modernizr to detect browser support for CSS transitions. Add the transitions styles above, then enable animated based on Modernizr’s detected support for transitions. This will allow browsers that support CSS transitions to use them, and browsers without support to use jQuery animation.

$('#masonry-container').masonry({
  // options...
  isAnimated: !Modernizr.csstransitions
});

Use the modernizr-rails gem to include Modernizr ;)

Or simply include masonry/modernizr-transitions in your javascript manifest.

Infinite scroll

Use with infinite-scroll which is included for convenience. All credits & license rights (MIT) to Paul Irish.

//= require masonry/jquery.infinitescroll.min

See infinite-scroll-jquery-plugin for configuration info.

Also see demo and source

Navigation for infinite scroll

Put a <nav> under your main container. This will trigger loading the next page!

<nav id="page-nav">
  <a href="../pages/2.html"></a>
</nav>

The link should load in a page containing elements that match .box

<div class="box col3">
  <p>Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.</p>
  <p>Vestibulum volutpat, lacus a ultrices sagittis,</p>
  <ul>
    <li>Lacus a ultrices sagittis</li>
    <li>Democratis</li>
    <li>Plummus</li>
  </ul>
</div>

These will be appended at the bottom of the #masonry-container. If you are using search with paging, be sure to update the page counter after each load somehow.

$(function(){

  var $container = $('#masonry-container');

  $container.imagesLoaded(function(){
    $container.masonry({
      itemSelector: '.box',
      columnWidth: 100
    });
  });

  $container.infinitescroll({
    navSelector  : '#page-nav',    // selector for the paged navigation
    nextSelector : '#page-nav a',  // selector for the NEXT link (to page 2)
    itemSelector : '.box',     // selector for all items you'll retrieve
    loading: {
        finishedMsg: 'No more pages to load.',
        img: 'http://i.imgur.com/6RMhx.gif'
      }
    },
    // trigger Masonry as a callback
    function( newElements ) {
      // hide new items while they are loading
      var $newElems = $( newElements ).css({ opacity: 0 });
      // ensure that images load before adding to masonry layout
      $newElems.imagesLoaded(function(){
        // show elems now they're ready
        $newElems.animate({ opacity: 1 });
        $container.masonry( 'appended', $newElems, true );
      });
    }
  );
});

The loader should be "on top". Here the loader is configured in the loading object as http://i.imgur.com/6RMhx.gif. This loader is included as an image asset at assets/images/masonry/loader.gif. So instead simply use:

img: '/assets/masonry/loader.gif'

Or whichever animated loader icon you want to use ;)

/* Infinite Scroll loader */
#infscr-loading {
  text-align: center;
  z-index: 100;
  position: fixed;
  left: 45%;
  bottom: 40px;
  width: 200px;
  padding: 10px;
  background: #000;
  opacity: 0.8;
  color: #FFF;
  -webkit-border-radius: 10px;
     -moz-border-radius: 10px;
          border-radius: 10px;
}

Kaminary paging

You can combine masonry infinite scroll with Kaminari using suggestions here:

In the above example, to enable paging simply have the pages/2.html link respond with the next page and infinite scroll will automatically ajax-retrieve and render the elements indicated by itemSelector into the container.

$container.masonry( 'appended', $newElems, true );

In the page returned, ensure it contains a #pagenav element with a link to the next page.

function( newElements ) {
  // `this` matches the element you called the plugin on (fx. #masonry-container)

  // get new #page-nav
  var nexPageNav = $(this).find('#page-nav');

  // substitute current #page-nav with new #page-nav from page loaded
  $('#page-nav').replaceWith(nexPageNav);

  # ...

See Create-Infinite-Scrolling-with-jQuery for another example.

Sausage which used in this example is also included with this gem for convenience ;)

Stylesheets: sausage/sausage.cssand sausage/sausage.reset.css

Javascript: masonry/jquery.sausagemin.min.js

For more see sausage info

The div with a class of 'page' is important for sausage. It is used to determine the different pages for the navigation on the right.

<div id="masonry-container" class="transitions-enabled infinite-scroll clearfix">
  <div class='page'>
    <%= render @articles %>
  </div>
</div>
<div class='article box col<%= article.size %>'>
  <h3><%= article.title %></h3>
  <div class='author'>by <%= article.author %></div>
  <div class='date'>by <%= article.created_at.to_s(:long) %></div>
  <p>
    <%= article.body %>
  </p>
</div>

Where article.size returns a valid col size, fx 1 to 5.

(function() {
  var page = 1,
      loading = false;

  function nearBottomOfPage() {
    return $(window).scrollTop() > $(document).height() - $(window).height() - 200;
  }

  $(window).scroll(function(){
    if (loading) {
      return;
    }

    if(nearBottomOfPage()) {
      loading=true;
      page++;
      $.ajax({
        url: '/articles?page=' + page,
        type: 'get',
        dataType: 'script',
        success: function() {
          $(window).sausage('draw');
          loading=false;
        }
      });
    }
  });

  $(window).sausage();
}());

It checks if the user scrolled to the bottom of the page. If that is the case, an ajax-request is sent to the `ArticlesController requesting the next page. After the ajax-request is completed successfully the sausage-navigation is redrawn.

When the ajax-request is sent to the ArticlesController we need to append the next page of articles. We need to create a file named index.js.erb to achieve this goal.

$("#masonry-container").append("<div class='page'><%= escape_javascript(render(@articles)) %></div>");

Note: You need to configure jQuery UI to use sausage.

See: railscast-endless-page for how to use endless pages with Rails using will_paginate gem.

jQuery pageless

jquery pageless could also be used...

The jquery pageless plugin is now provided as masonry/jquery.pageless.min.js. The [repo]((https://github.com/jney/jquery.pageless) demonstrates how to use pageless with Rails 3.

Use with images

See image demo which uses imagesLoaded plugin (included - see below)

Images Loaded plugin

See repo

A jQuery plugin that triggers a callback after all the selected/child images have been loaded. Because you can't do .load() on cached images.

//= require masonry/jquery.imagesloaded.min

Also included is the loremimages plugin, useful for testing purposes ;)

Contributing to masonry-rails

  • Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
  • Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
  • Fork the project.
  • Start a feature/bugfix branch.
  • Commit and push until you are happy with your contribution.
  • Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
  • Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

Copyright

Copyright (c) 2012 Kristian Mandrup. See LICENSE.txt for further details.

More Repositories

1

cantango

CanCan extension with role oriented permission management, rules caching and much more
Ruby
407
star
2

cream

Integrates Devise, Roles and CanCan with Permits for a Rails 3 app
Ruby
295
star
3

schema-to-yup

Schema to Yup validation
JavaScript
277
star
4

datascript-tutorial

Datascript and Datomic tutorial book
206
star
5

mongoid-geo

Geo-spatial extension for Mongoid 2
Ruby
120
star
6

haversine

Calculates the haversine distance between two locations using longitude and latitude
Ruby
89
star
7

vue2-dragula-demo

Vue2 demo app for vue-dragula plugin
JavaScript
78
star
8

gmaps-autocomplete-rails

Google Maps v3 search with jQuery UI Autocomplete, ready for use with Rails asset pipeline
Ruby
73
star
9

geo_magic

Location from IP, geocoding, distance calculation, and geo/map utilities
Ruby
69
star
10

acts_as_list_mongoid

Make your Mongoid model acts as a list
Ruby
64
star
11

roles_generic

Generic role model strategies sharing same API easy to insert in any model
Ruby
59
star
12

rails-gallery

Popular javascript photo gallery and carousel components ready for use with Rails 3 and above :)
Ruby
53
star
13

geo-distance

Calculates the geo distance between two locations using longitude and latitude, using Haversine, Speherical or Vincenty formula
Ruby
52
star
14

ui_datepicker-rails3

jQuery UI datepicker integration for Formtastic, Simple Form and Active Admin
Ruby
50
star
15

world-flags

Use world flag sprites in your Rails 3 app
HTML
48
star
16

mm-devise

Mongo Mapper integration for Devise framework
Ruby
47
star
17

amazing-aurelia-book

Book on how to write advanced, high powered apps with the Aurelia framework.
41
star
18

troles

Roles for Rails 3
Ruby
41
star
19

json-schema-to-es-mapping

Convert JSON Schema to Elastic Search mapping schema
JavaScript
38
star
20

generator-aurelia-ts

Turbo Start generator for Aurelia apps
JavaScript
31
star
21

roles_mongoid

Roles for mongoid using the Roles generic API from roles_generic
Ruby
29
star
22

emberjs-plugin

EmberJS plugin for Intellij IDEA and Webstorm IDE
Java
28
star
23

sugar-high

More Ruby sugar - inspired by the 'zuker' project
Ruby
26
star
24

ember-konacha-rails

Generate Konacha spec infrastructure for your Ember-Rails apps
Ruby
24
star
25

papertrail_mongoid

Papertrail for mongoid
Ruby
23
star
26

cancan-permits

Role specific Permits for use with CanCan permission system
Ruby
21
star
27

auth-assistant

Assistance for configuring and use of devise and cancan in combination
Ruby
20
star
28

vue-framer

Bridging the final gap of the design to app workflow, making a Framer app work with Vue
JavaScript
20
star
29

roles_active_record

Roles for Active Record implementing the Roles generic API
Ruby
18
star
30

slush-reframe

Reframe generator for base application and main artifacts such as domain models
JavaScript
17
star
31

jquery-ui-bootstrap-rails

jQuery UI Bootstrap for Rails asset pipeline
Ruby
17
star
32

bootstrap-addons-rails

Twitter Bootstrap addons: Color- and Datepicker, Image gallery, ready for use with Rails asset pipeline
Ruby
17
star
33

mongoid_embedded_helper

Facilitates performing queries on collections in embedded Mongoid documents
Ruby
16
star
34

mongo_rails3_gen

Mongo DB rails 3 generators to setup use of Mongo DB and create Mongo DB compatible models in Rails 3
Ruby
16
star
35

aurelia-rethink-bindtable

Aurelia bind table integration for RethinkDB via Socket.io
JavaScript
16
star
36

rails3-templates

Rails 3 templates for rapid creation of Rails 3 applications
Ruby
15
star
37

cantango-permits

Permits and Permit engine for CanTango
Ruby
15
star
38

bs-xstate

Bucklescript bindings for XState state machine
OCaml
15
star
39

world-flag-packs

World Flag image packs for use on the web or with the world-flags rails gem
15
star
40

json-schema-to-graphql-types-decorated

Convert JSON schema to GraphQL types (string) including GraphQL transforms/directives
JavaScript
14
star
41

very_nifty_generators

Rails 3 very nifty generators using very DRY conventions
Ruby
14
star
42

geo_calc

Geo calculations in ruby and javascript
Ruby
14
star
43

ember-pusher

A nice little Ember - Pusher integration library
Ruby
14
star
44

vue2-apollo-scaphold

Vue2 Apollo Scaphold.io starter app
Vue
13
star
45

gun-edge

API helpers for Gun.js
JavaScript
13
star
46

pie-rails

Progressive Internet Explorer (PIE) ready for use with Rails asset pipeline
Ruby
13
star
47

react-16.nim

React 16.x bindings for Nim 1.0 with example app (WIP)
Nim
13
star
48

timespan

Use TimeSpans in ruby
Ruby
13
star
49

cartling

Shopping Cart system for Node.js using Keystone and MongoDB by default
JavaScript
12
star
50

ember-beercan

Authorization a-la cancan style for Ember with some Authentication magic added for good measure ;)
Ruby
12
star
51

convert-json-schema-to-mongoose

Convert JSON schema to mongoose 5 schema
JavaScript
12
star
52

prawn_html

A prawn library to assist in converting html to pdf using prawn for pdf rendering
Ruby
11
star
53

cream-app-active_record

Cream demo app for Rails 3 with ActiveRecord
Ruby
11
star
54

react-mxgraph-typescript-starter

React 16 mxgraph-js and typescript starter template based on create-react-app
TypeScript
11
star
55

cypher-query

Javascript Cypher query engine for graphs such as graphology and gun
TypeScript
11
star
56

cantango-demo

Cantango Rails 3 demo app with devise integration
Ruby
11
star
57

Prawn-assist

Helper functions to parse HTML and create output to assist rendering PDF using prawn (or some other renderer)
Ruby
11
star
58

semantic-sass-bootstrap

Semantic SASS wrapper for Twitter Bootstrap
Ruby
11
star
59

chain-gun

Gun.js chain API extensions
JavaScript
10
star
60

mongoid_adjust

Adds simple adjust! method to Mongoid - in the near future it should use the built-in Mongo DB functionality
Ruby
10
star
61

FirebaseUI

FirebaseUI wrapped for use with React Native (iOS only)
Objective-C
9
star
62

acts_as_tree_rails3

The old acts_as_tree updated and converted into a gem for rails 3
Ruby
9
star
63

mongoid-serializer

Add some sane controller serialization support for your Mongoid 3+ models
Ruby
9
star
64

permit-authorize

Authorization library for Javascript and NodeJS using permits and user abilities
LiveScript
9
star
65

cancan-rest-links

Rest link helpers for CanCan
Ruby
9
star
66

ember-config

Yeoman generator for ember-cli to facilitate configuring an Ember app with various asset compilers, components, layout frameworks etc.
JavaScript
9
star
67

money-mongoid

Standalone Mongoid support and integration for the Money gem
Ruby
9
star
68

ruby_traverser_dsl

A ruby code traverser DSL for finding and traversing ruby code as an object model using a nice DSL - uses ripper2ruby
Ruby
9
star
69

rspec-action_view

RSpec addon to simplify creating specs for Rails 3 ActionView extensions
Ruby
8
star
70

cream-app-mongoid

Cream 7.7 demonstration app
Ruby
8
star
71

awd-rails-4th-depot-app

Agile web development with Rails 4th edition - Depot application
Ruby
8
star
72

authorize-mw

Authorization middleware for Node.js and Javascript platform in general (with a little twist)
LiveScript
8
star
73

cancan-permits-demo

Demo of how to use cancan-permits in a Rails 3 app
Ruby
8
star
74

ember-easyform-cli

Experimental fork of ember-easyForm to wrap it as an Ember CLI addon for easy installation
JavaScript
8
star
75

typescript-ast-processor

Process a TypeScript AST using visitors, collectors and instrumentation
TypeScript
7
star
76

red-elements

Node-red UI components as native custom elements
TypeScript
7
star
77

sweetloader

Sweetens up your autoloading of classes and modules
Ruby
7
star
78

ember-factories

Simple Factory library for use with Ember.js
Ruby
7
star
79

geokit-rails3-mongoid

Geokit for Rails 3 using Mongoid
Ruby
7
star
80

facebook-social_plugins

Facebook HTML5 style social plugins for Rails 3
Ruby
7
star
81

ember-cli-emberscript

Adds precompilation of EmberScript files and all the basic generation types to the ember generate command.
JavaScript
7
star
82

rubyproject

A Thor based generator for generating a skeleton Ruby project with Rspec and Cucumber on by default
Ruby
7
star
83

json-schema-model-builder

Infrastructure components to easily process JSON schema and build models from it
JavaScript
7
star
84

semantic-ui-page-layouts

Semantic UI page layouts for common scenarios
HTML
6
star
85

log4r-color

log4r now with color outputs to terminal/console
Ruby
6
star
86

credit_card_icons

Credit card icons for Rails 3 as an engine, using CSS sprites with icons in various sizes and shapes
Ruby
6
star
87

easy_as_pie

Rails asset wrapper for jQuery easy-pie-chart
Ruby
6
star
88

rspec-book-movie-app

The RSpec book movie app implemented for Rails 3 and Rspec 2 with Capybara
Ruby
6
star
89

water-gun

Gun.js API extensions for working with Observables/Streams and CSP channels
JavaScript
6
star
90

rspec-book-views-example

RSpec book views example for RSpec 2.beta11 with Rails 3.b3 and Capybara
Ruby
6
star
91

netzke_widget_generators

Rails 3 generators to quickly generate skeletons for custom Netzke widgets
Ruby
6
star
92

future-gun

Gun.js extensions for Promise and async/await based flow control
JavaScript
6
star
93

concerned

Concerns for Rails
Ruby
5
star
94

cantango-core

The core functionality of CanTango
Ruby
5
star
95

ember-bootstrap-rails

Add ember-bootstrap to your Rails 3.1+ Assets pipeline
JavaScript
5
star
96

koa-marko-example

Convenient Koa.js server setup for rendering pages of a multi page application
JavaScript
5
star
97

ember-big_project

Create a sensible and extensible Ember project structure for big projects ;)
Ruby
5
star
98

aurelia-definitely-typed

Aurelia definition files for registration with TypeScript Definitely Typed registry for use with tsd package manager
TypeScript
5
star
99

geo_point

A GeoPoint encapsulates latitude, longitude and various geo calculations relative to itself
Ruby
5
star
100

qiankun-demo

Qiankun demo app - single-spa Micro Front End (MFE) application
JavaScript
5
star