Images not stacking up in Masonry template? - javascript

So apparently my images are not stacking up on top of each other. They are all in straight horizontal rows. Not sure what is wrong. I want the images to be stacked up on top of each other in a fitted Pinterest-like/Masonry grid.
Here's the shortcode I use in my index file:
echo do_shortcode('[nggallery id="1"]');
Here's the code found in my Masonry gallery template file:
<?php
/**
Template Page for the gallery overview
Follow variables are useable :
$gallery : Contain all about the gallery
$images : Contain all images, path, title
$pagination : Contain the pagination content
You can check the content when you insert the tag <?php var_dump($variable) ?>
If you would like to show the timestamp of the image ,you can use <?php echo $exif['created_timestamp'] ?>
**/
?>
<script src="/wp-includes/js/jquery/jquery.masonry.min.js" type="text/javascript"> </script>
<script>
$(function(){
var $container = $('#container');
$container.imagesLoaded( function(){
$container.masonry({
itemSelector : '.box'
});
});
});
</script>
<style>
.brick {
display: block;
margin: 0px 10px 15px 10px;
float:left;
/* width:250px; */
height: auto;
}
</style>
<script>
jQuery( document ).ready( function( $ ) {
$('#wall').masonry({
// options
itemSelector : '.brick',
isAnimated: true,
animationOptions: {
duration: 500,
easing: 'linear',
queue: false}
});
</script>
<?php if (!defined ('ABSPATH')) die ('No direct access allowed'); ?><?php if (!empty ($gallery)) : ?>
<div class="ngg-galleryoverview" id="<?php echo $gallery->anchor ?>">
<div id="wall">
<!-- Thumbnails -->
<?php $i = 0; ?>
<?php foreach ( $images as $image ) : ?>
<div class="brick">
<a class="thickbox" href="<?php echo $image->imageURL ?>" title="<?php echo $image->description ?>" <?php echo $image->thumbcode ?> >
<?php if ( !$image->hidden ) { ?>
<img title="<?php echo $image->alttext ?>" alt="<?php echo $image->alttext ?>" src="<?php echo $image->thumbnailURL ?>" <?php echo $image->size ?> />
<?php } ?>
</a>
</div>
<?php if ( $image->hidden ) continue; ?>
<?php if ($gallery->columns > 0): ?>
<?php if ((($i + 1) % $gallery->columns) == 0 ): ?>
<br style="clear: both" />
<?php endif; ?>
<?php endif; ?>
<?php $i++; ?>
<?php endforeach; ?>
<?php echo $pagination ?>
</div>
</div>
<?php endif; ?>
This is what my gallery looks like on the actual page:
http://steppic.com/original/896e07bdf2f759709b9ccc5f9eea9e28.png

You are calling masonry twice with different parameters.
The first, your container is "#container" and your items are ".box":
var $container = $('#container');
$container.imagesLoaded( function(){
$container.masonry({
itemSelector : '.box'
});
In the second, your container is "#wall" and your items are ".brick", and you left out "});" at the end of your (document).ready
jQuery( document ).ready( function( $ ) {
$('#wall').masonry({
// options
itemSelector : '.brick',
isAnimated: true,
animationOptions: {
duration: 500,
easing: 'linear',
queue: false}
});
}); //this was missing
Pick the correct container and items and it should work

I'm not completely sure as I don't know if you provided the complete CSS, but maybe it will work if you just remove the margin: 0px 10px 15px 10px; for class brick.
On the masonry example page I just adjusted an example by adding this margin to the class item which corresponds to your class brick, and the result looks similar to your screenshot:
Masonry Example
In addition, it looks like you call masonry twice - one time for .container - $container.masonry({..., and a second time for #wall - $('#wall').masonry({...
You could check if it's working like intended when you remove the margin as suggested and maybe also call masonry only once.
Update: Next adjustment you can try is to remove height: auto; from class brick.
I've adjusted a masonry example by adding height: auto to class item: Masonry with height: auto, as you will notice, there are some issues not present when the setting for height is removed: Masonry without height: auto
For masonry reference: http://masonry.desandro.com/options.html

Related

Isotope gutter-sizer collapses when filter button is clicked

I have an Isotope filter working with WordPress to filter posts. It uses a masonry layout with a gutter-sizer set as a percentage in the CSS. It all works fantastically on page load until I click something on the filter and then the gutter gap collapses and does't work again until I reload the page or if I resize the browser window.
Any help would be much appreciated, I'm totally lost!
Here's how I'm initialising the code:
$( function() {
$('.container').isotope({
itemSelector: '.item',
percentPosition: true,
layoutMode: 'masonry',
masonry: {
columnWidth: '.grid-sizer',
gutter: '.gutter-sizer'
}
})
});
Edit:
Here's the CSS
.gutter-sizer {
width: 1.7241379%;
}
.item, .grid-sizer {
width: 100%; // width of each brick less the padding inbetween
margin-bottom: 20px;
#include border-radius(2px);
#include shadow;
background-color: $white;
#media only screen and (min-width: 600px) {
width: 49.13793105%;
}
#media only screen and (min-width: 900px) {
width: 23.7068966%;
}
}
And here is the code for the filter and the masonry posts:
<!-- #filter-menu --> <nav id="filter-navigation" class="main-filter-navigation item" role="navigation">
<button class="filter-toggle"><?php _e( 'Filter', 'cambridgerules' ); ?><i class="fa fa-filter"></i></button>
<ul class="filters">
<li class="filter-all">All</li>
<li class="interpret-filter-label">Interpreted Worldwide:</li>
<?php
$terms = get_terms("type"); // get all categories, but you can use any taxonomy
$count = count($terms); //How many are they?
if ( $count > 0 ){ //If there are more than 0 terms
foreach ( $terms as $term ) { //for each term:
echo "<li class='".$term->slug."'><a href='#' data-filter='.".$term->slug."'>" . $term->name . "</a></li>\n";
//create a list item with the current term slug for sorting, and name for label
}
}
?>
</ul>
</nav><!-- #filter-menu -->
<div class="container">
<div class="grid-sizer"></div>
<div class="gutter-sizer"></div>
<?php $the_query = new WP_Query( array(
'showposts' => 50,
'post_type' => array('interpreted')
)
); //Check the WP_Query docs to see how you can limit which posts to display ?>
<?php if ( $the_query->have_posts() ) : ?>
<div id="isotope-list">
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$termsArray = get_the_terms( $post->ID, "type" ); //Get the terms for this particular item
$termsString = ""; //initialize the string that will contain the terms
foreach ( $termsArray as $term ) { // for each term
$termsString .= $term->slug.' '; //create a string that has all the slugs
}
?>
<div class="<?php echo $termsString; ?> item"> <?php // 'item' is used as an identifier (see Setp 5, line 6) ?>
<h3><?php the_title(); ?></h3>
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();
} ?>
</div> <!-- end item -->
<?php endwhile; ?>
</div> <!-- end isotope-list -->
<?php endif; ?>
</div> <!-- end container -->
Ok, sorted it out by using the following code:
jQuery(function ($) {
var $container = $('.container'); //The ID for the list with all the blog posts
$container.isotope({ //Isotope options, 'item' matches the class in the PHP
itemSelector : '.item',
layoutMode : 'masonry',
masonry: {
columnWidth: '.grid-sizer',
gutter: '.gutter-sizer'
}
});
//Add the class selected to the item that is clicked, and remove from the others
var $optionSets = $('.filters'),
$optionLinks = $optionSets.find('a');
$optionLinks.click(function(){
var $this = $(this);
// don't proceed if already selected
if ( $this.hasClass('selected') ) {
return false;
}
var $optionSets = $this.parents('.filters');
$optionSets.find('.selected').removeClass('selected');
$this.addClass('selected');
//When an item is clicked, sort the items.
var selector = $(this).attr('data-filter');
$container.isotope({ filter: selector });
return false;
});
});

Yii Register JS Variables

I am using HumHub, based on Yii, and trying to set a JS variable with a URL extracted from a function that enriches text.
Currently, the variable doesn't seem to be getting set in the model, so I haven't even really begin to work on the script.
It should fetch OpenGraph data eventually, but I can't even get the URL to the script I intend to debug and use.
Base enrichText function
/**
* Converts an given Ascii Text into a HTML Block
* #param boolean $allowHtml transform user names in links
* #param boolean $allowEmbed Sets if comitted video links will embedded
*
* Tasks:
* nl2br
* oembed urls
*/
public static function enrichText($text, $from = 'default', $postid = '')
{
if ( $from == 'default' ) {
$maxOembedCount = 3; // Maximum OEmbeds
$oembedCount = 0; // OEmbeds used
// Parse bbcodes before link parsing
$text = self::parseBBCodes($text);
$text = preg_replace_callback('/(?<!\])(https?:\/\/.*?)(\s|$)(?!\[)/i', function ($match) use (&$oembedCount, &$maxOembedCount) {
// Try use oembed
if ($maxOembedCount > $oembedCount) {
$oembed = UrlOembed::GetOembed($match[0]);
if ($oembed) {
$oembedCount++;
return $oembed;
}
}
$regurl = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// Check if there is a url in the text independently and render to JS var
if(preg_match($regurl, $text, $url)) {
if (!empty($postid)) {
Yii::app()->clientScript->setJavascriptVariable("ourl".$postid, $url[0]);
}
}
return HHtml::link($match[1], $match[1], array('target' => '_blank')).$match[2];
}, $text);
// get user and space details from guids
$text = self::translateMentioning($text, true);
// create image tag for emojis
$text = self::translateEmojis($text);
return nl2br($text);
} else {
// Parse bbcodes before link parsing
$text = self::parseBBCodes($text, $from);
return $text;
}
}
Calling info
<?php
/**
* This view represents a wall entry of a post.
* Used by PostWidget to show Posts inside a wall.
*
* #property User $user the user which created this post
* #property Post $post the current post
*
* #package humhub.modules.post
* #since 0.5
*/
?>
<div class="panel panel-default post" id="post-<?php echo $post->id; ?>">
<div class="panel-body">
<?php $this->beginContent('application.modules_core.wall.views.wallLayout', array('object' => $post)); ?>
<span id="post-content-<?php echo $post->id; ?>" style="overflow: hidden; margin-bottom: 5px;">
<?php print HHtml::enrichText($post->message, 'default', $post->id); ?>
</span>
<a class="more-link-post hidden" id="more-link-post-<?php echo $post->id; ?>" data-state="down"
style="margin: 20px 0 20px 0;" href="javascript:showMore(<?php echo $post->id; ?>);"><i
class="fa fa-arrow-down"></i> <?php echo Yii::t('PostModule.widgets_views_post', 'Read full post...'); ?>
</a>
<div id="opengraph-<?php echo $post->id; ?>" class="opengraph-container">
<div class="opengraph-img-<?php echo $post->id; ?>"></div>
<div class="opengraph-body">
<h2 class="opengraph-heading-<?php echo $post->id; ?>"></h2>
<div class="opengraph-content-<?php echo $post->id; ?>"></div>
</div>
</div>
<?php $this->endContent(); ?>
</div>
</div>
<script type="text/javascript">
console.log('Oembed URL for <?php echo $post->id; ?>: '+ourl<?php echo $post->id; ?>);
// ... etc
Update I was able to pass the variable by adding a script to the end of the text. Very, very dirty method. I was hoping for something much cleaner. :(
/**
* Converts an given Ascii Text into a HTML Block
* #param boolean $allowHtml transform user names in links
* #param boolean $allowEmbed Sets if comitted video links will embedded
*
* Tasks:
* nl2br
* oembed urls
*/
public static function enrichText($text, $from = 'default', $postid = '')
{
if ( $from == 'default' ) {
$maxOembedCount = 3; // Maximum OEmbeds
$oembedCount = 0; // OEmbeds used
// Parse bbcodes before link parsing
$text = self::parseBBCodes($text);
$text = preg_replace_callback('/(?<!\])(https?:\/\/.*?)(\s|$)(?!\[)/i', function ($match) use (&$oembedCount, &$maxOembedCount) {
// Try use oembed
if ($maxOembedCount > $oembedCount) {
$oembed = UrlOembed::GetOembed($match[0]);
if ($oembed) {
$oembedCount++;
return $oembed;
}
}
return HHtml::link($match[1], $match[1], array('target' => '_blank')).$match[2];
}, $text);
// get user and space details from guids
$text = self::translateMentioning($text, true);
// create image tag for emojis
$text = self::translateEmojis($text);
$regurl = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// Check if there is a url in the text independently and render to JS var
if(preg_match($regurl, $text, $url)) {
if (!empty($postid)) {
$text .= '<script type="text/javascript"> var ourl'.$postid.' = \''.$url[0].'\'; </script>';
}
}
return nl2br($text);
} else {
// Parse bbcodes before link parsing
$text = self::parseBBCodes($text, $from);
return $text;
}
}
Update 2: Attempt to grab Opengraph data
Here i attempt to grab the data from opengraph with the supposed set variable in the HHtml::enrichText() return. However I get the error: SyntaxError: expected expression, got '<' jquery.js:1 pointing to the first line of the jquery file, which is the commenting and license of the script.
The script also doesn't show in source code
<?php
/**
* This view represents a wall entry of a post.
* Used by PostWidget to show Posts inside a wall.
*
* #property User $user the user which created this post
* #property Post $post the current post
*
* #package humhub.modules.post
* #since 0.5
*/
?>
<div class="panel panel-default post" id="post-<?php echo $post->id; ?>">
<div class="panel-body">
<?php $this->beginContent('application.modules_core.wall.views.wallLayout', array('object' => $post)); ?>
<span id="post-content-<?php echo $post->id; ?>" style="overflow: hidden; margin-bottom: 5px;">
<?php print HHtml::enrichText($post->message, 'default', $post->id); ?>
</span>
<a class="more-link-post hidden" id="more-link-post-<?php echo $post->id; ?>" data-state="down"
style="margin: 20px 0 20px 0;" href="javascript:showMore(<?php echo $post->id; ?>);"><i
class="fa fa-arrow-down"></i> <?php echo Yii::t('PostModule.widgets_views_post', 'Read full post...'); ?>
</a>
<div id="opengraph-<?php echo $post->id; ?>" class="opengraph-container">
<div class="opengraph-img-<?php echo $post->id; ?>"></div>
<div class="opengraph-body">
<h2 class="opengraph-heading-<?php echo $post->id; ?>"></h2>
<div class="opengraph-content-<?php echo $post->id; ?>"></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
(function() {
var opengraph = "http://bfxsocial.strangled.net/resources/Opengraph/getInfo.php?callback=?";
$.getJSON( opengraph, {
href: ourl<?php echo $post->id; ?>,
format: "json"
})
.done(function( data ) {
console.log('<?php echo Yii::t('PostModule.widgets_views_post', 'Opengraph: Response from: '); ?>'+ourl-<?php echo $post->id; ?>+"\n\n"+data);
var img = $('<img />',{ id: 'og:img-<?php echo $post->id; ?>', src: data['og:image'], alt:'data.title'}).appendTo($('.opengraph-img-<?php echo $post->id; ?>'));
$('.opengraph-heading-<?php echo $post->id; ?>').html(data.title);
$('.opengraph-body-<?php echo $post->id; ?>').html(data.description);
$('#opengraph-<?php echo $post->id; ?>').show();
});
})();
});
</script>
</div>
<?php $this->endContent(); ?>
</div>
</div>
<!-- Opengraph Temp Style -->
<style type="text/css">
.opengraph-container
display: none;
width: 100%;
padding: 3px;
margin: 5px;
background-color: rgba(0,0,0,0.1);
border: 1px solid rgba(150,150,150,0.1);
}
.opengraph-img {
display: block;
min-width: 99%;
max-height: 350px;
margin: 0 auto;
}
.opengraph-body {
width: 99%;
padding-top: 5px;
border-top: 1px solid rgba(0,0,0,0.1);
}
.opengraph-heading {
display: block;
width: 250px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.opengraph-content {
font-size: 12px;
color: #7F7F7F;
}
</style>
<!-- End: Opengraph Temp Style -->

Slide to left ul li via JavaScript

I have this structure:
<div style="background-color:#FFF;height:49px;border-top:1px solid #ef4723;clear:both">
<div id="marka-slider" class="row">
<ul>
<?php if (($references = Reference::getAll())) :
foreach ($references as $r) :
?>
<li>
<img src="<?php echo Reference::getUploadPath() . '/' . $r->mediapath; ?>"
alt="<?php echo $r->title; ?>" title="<?php echo $r->title; ?>"/>
<!-- <?php CVarDumper::dump(array('ref: ' => $r->attributes), 5, 1); ?> -->
</li>
<?php endforeach; ?>
<?php endif; ?>
</ul>
</div>
</div>
JS:
var slider;
$(document).ready(function () {
slider = $('#marka-slider ul li');
setTimeout(function() {
bgscroll('right');
}, 1000);
});
function bgscroll(direction) {
var sign;
if (direction === 'left') {
slider.stop().animate({'background-position': '+=10000'}, 200000, 'linear', bgscroll);
} else {
slider.stop().animate({'background-position': '-=10000'}, 200000, 'linear', bgscroll);
}
But it isn't working. When I check via Firebug, it doesn't give a error. How can I solve it?
DEMO
http://jsfiddle.net/xpVRT/2/
You were animating background image of the li tag, while the images were inside li in the img tags.

Set max horizontal scroll of div

I have a jquery images scroller below that just scrolls horizontally left/right. The loop below could include an infinite number of images.
The problem I have is that while it scrolls left and right fine, once the images end you can just keep scrolling so essentially you're just scrolling over white space!
How can I set a max scroll so that when the images end it won't allow it to scroll anymore? Obviously the number of images is dynamic so it can have 1 or 100 images in there.
<div id="imgThumbs" class="scroller" style="position:relative;height:75px;width: 306px; overflow: hidden; white-space: nowrap;">
<a href="#" id="left-button" style="left:14px;top:25px;position:absolute;">
<img src="left-button.png" width="20" height="20" />
</a>
<a href="#" id="right-button" style="right:14px;top:25px;position:absolute;">
<img src="right-button.png" width="20" height="20" />
</a>
<div id="contentScroller">
<?php $counter = 1; while(the_repeater_field('images')): ?>
<a class="fancybox" rel="group" href="<?php echo the_sub_field('high_resolution_image'); ?>" style="text-decoration:none!IMPORTANT;color:white!IMPORTANT;" class="showImg">
<img class="image-<?php echo $counter; ?>" src="<?php echo the_sub_field('image'); ?>" width="90" height="68" alt="<?php echo the_title(); ?> <?php echo $counter; ?>" />
</a>
<?php $counter++; endwhile; ?>
</div>
</div>
<script>
jQuery(document).ready(function ($) {
$('#right-button').click(function() {
$('#contentScroller').animate({
marginLeft: "-=306px"
}, "fast");
});
$('#left-button').click(function() {
$('#contentScroller').animate({
marginLeft: "+=306px"
}, "fast");
});
});
</script>
UPDATE
Here's a fiddle - http://jsfiddle.net/jCskY/2/
Compare the marginLeft with the width calculated by the sum of content a's widths.
If the margin passes the width, it should hide the button. Otherwise, it should show.
Here is a snippet of how it would be implemented.
Also, see this fiddle, for live example!
var updateRightLeftButtons = function() {
if (306 > (parseInt($('#contentScroller').css('marginLeft')) * -1)) {
$('#left-button').hide();
} else {
$('#left-button').show();
}
if ((($('#contentScroller a').width() * $('#contentScroller a').length) - 306) < (parseInt($('#contentScroller').css('marginLeft')) * -1)) {
$('#right-button').hide();
} else {
$('#right-button').show();
}
};
$('#right-button').click(function() {
updateRightLeftButtons();
if ($(this).is(':visible'))
$('#contentScroller').animate({
marginLeft: "-=306px"
}, "fast", updateRightLeftButtons);
});
$('#left-button').click(function() {
updateRightLeftButtons();
if ($(this).is(':visible'))
$('#contentScroller').animate({
marginLeft: "+=306px"
}, "fast", updateRightLeftButtons);
});
updateRightLeftButtons();​
<?php
$dirname = '_/img/album';
$pattern = "/(\.jpg$)/i"; // valid image extensions
if (is_dir($dirname)) {
if ($handle = opendir($dirname)) {
$count = 0;
while (false !== ($file = readdir($handle))) {
// if this file is a valid image
if (preg_match($pattern, $file)) {
$count++;
}
}
closedir($handle);
}
}
?>
then take the count multiplied by 20 and set the value to the width of div container

Problem changing background image using Javascript

I'm trying to change the background image of a link when it is clicked via Javascript. I five tabs and when the user clicks on a tab, I want the background image of that tab to change to a plain white image. Where as the other four tabs should be changed to a grey image.
So my CSS is as follows:
.listingindex li a {
background:url(../images/tabe-nomal.jpg) left top no-repeat;
color:#333333;
display: inline-block;
text-decoration:none;
width:229px;
padding:14px 0px 14px 10px;
}
.listingindex li a:hover {
background:url(../images/tabe-over.jpg) left top no-repeat;
}
and my code looks like this:
<div class="listingindex">
<?php
$catId = get_cat_id('featured');
$childOf = 'child_of='.$catId;
$subCats = get_categories($childOf);
// Slice array so only 5 categories can be displayed.
$subCats = array_slice($subCats, 0, 5);
foreach ($subCats as $value) {
$subCatsStr .= $value->cat_ID.'|';
}
foreach ($subCats as $subCat) {
?>
<ul>
<li><a id="tab_<?=$subCat->cat_ID?>" href="javascript:toggle(<?=$subCat->cat_ID?>,'<?=$subCatsStr?>')"><?=$subCat->name?></a></li>
</ul>
<ul id="thumbnails_<?=$subCat->cat_ID?>" class="listingarea">
<?php $query = new WP_Query('category_name='.$subCat->name.'&posts_per_page=9');
while( $query->have_posts() ) : $query->the_post();?>
<li>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?
$id = $post->ID;
$filename = $_SERVER["DOCUMENT_ROOT"].'/xxxxxxx/xxxxxx/xxxxx/xxxxxx/images/thumbnails/image_'.$id.'.jpg';
if (file_exists($filename)) {
?><img src="<?php echo $templateDir; ?>/images/thumbnails/image_<?=$id;?>.jpg" alt="Image_<?=$id;?>" /><?
}else{
?><img src="<?php echo $templateDir; ?>/images/thumbnails/no_image.jpg" alt="No Image" /><?
}?>
</a>
</li>
<?php endwhile; ?>
</ul>
<?}?>
</div>
Lastly my JS looks like this:
function toggle(catID, subCatsStr) {
document.getElementById('thumbnails_'+catID).style.display = "block";
document.getElementById('tab_'+catID).style.backgroundImage = "url(/images/tabe-over.jpg)";
subCatsArr = subCatsStr.split('|');
for (i = 0; i <= subCatsArr.length - 2; i++){
if (subCatsArr[i] != catID){
document.getElementById('thumbnails_'+subCatsArr[i]).style.display = "none";
document.getElementById('tab_'+catID).style.backgroundImage = "url(images/tabe-nomal.jpg) left top no-repeat";
}
}
}
At the moment, this code simply removes the grey image (tabe-nomal.jpg) when a tab is clicked.
Any help appreciated.
Regards...
Looks like your backgroundImage urls might not be correct -- try using the same path (../images/..) as in your initial css rule
To solve the problem in the end I had to specify the full path name:
document.getElementById('tab_'+catID).style.backgroundImage = "url(http://www.xxxxxx.ie/xxxxxxx/wp-content/themes/xxxxxxx/images/tabe-over.jpg)";
Not sure why, but this solved the problem. Its a Wordpress theme so maybe this had something to do with it.

Categories

Resources