I'm try to add dynamically packery item by click
method. All every thing is working fine except on a single click packery add three new items. My question is how to add one item on single click?
Method
Demo
Thanks.
Edit
After page load grid items is Five. See the picture below.
When click
the Append items button
packery will add more three items. See the picture below.
Snippet
var $grid = $('.grid').packery({
itemSelector: '.grid-item'
});
$('.append-button').on( 'click', function() {
// create new item elements
var $items = getItemElement().add( getItemElement() ).add( getItemElement() );
// append elements to container
$grid.append( $items )
// add and lay out newly appended elements
.packery( 'appended', $items );
});
// make <div class="grid-item grid-item--width# grid-item--height#" />
function getItemElement() {
var $item = $('<div class="grid-item"></div>');
// add width and height class
var wRand = Math.random();
var hRand = Math.random();
var widthClass = wRand > 0.85 ? 'grid-item--width3' : wRand > 0.7 ? 'grid-item--width2' : '';
var heightClass = hRand > 0.85 ? 'grid-item--height3' : hRand > 0.5 ? 'grid-item--height2' : '';
$item.addClass( widthClass ).addClass( heightClass );
return $item;
}
* { box-sizing: border-box; }
body { font-family: sans-serif; }
/* ---- grid ---- */
.grid {
background: #DDD;
max-width: 1200px;
}
/* clear fix */
.grid:after {
content: '';
display: block;
clear: both;
}
/* ---- .grid-item ---- */
.grid-item {
color: #ffffff;
text-align: center;
font-size: 30px;
line-height: 80px;
float: left;
width: 80px;
height: 80px;
background: #C09;
border: 2px solid hsla(0, 0%, 0%, 0.5);
}
.grid-item--width2 { width: 160px; }
.grid-item--height2 { height: 160px; line-height: 160px; }
.grid-item--width3 { width: 240px; }
.grid-item--height3 { height: 240px; }
button { font-size: 20px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://mfzy.co/packery.pkgd.js"></script>
<h1>Packery - appended</h1>
<div class="grid">
<div class="grid-item grid-item--width2">1</div>
<div class="grid-item grid-item--height2">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item grid-item--height2">5</div>
</div>
<p><button class="append-button">Append items</button></p>
My Question:
How can I control append items? I want to add dynamically one item not three items on single click
.
Note:
Don't submit the down vote if you failed to submit solution for it.
Strange question. Just remove two of elements out of the code.
var $items = getItemElement();
http://codepen.io/anon/pen/egbLxQ
I don't understand what you trying todo in this line?
var $items = getItemElement().add( getItemElement() ).add( getItemElement() );
if you change it to this:
var $items = getItemElement();
only one element will be added.
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With