I'm trying to match div heights with jquery while importing content from a JSON file. Upon the first view of the page the match height finishes loading before all the content from the JSON file can finish loading in. As a result, the images from the JSON file get cut off by the .grid-item div. Once all the JSON content has loaded in I can resize the browser window or reload the page and the match height works properly. But if I empty cache and hard reload the match height will finishing loading again before the JSON content can finish loading.
I've tried putting the .matchHeight outside of the $.getJSON, which allows all the content to load from the JSON file but for some reason doesn't match the height for each div. Each div has their own height.
How do I tell the .matchHeight to wait until all of the JSON content has finished loading upon first view of the page?
I'm using the jquery.matchHeight.js code from GitHub.
Javascript
$(document).ready(function() {
$.getJSON( "locations.json", function( data ) {
var htmlcontent = "";
$.each( data.locations, function( key, index ) {
var name = index.locationName;
var state = index.locationState;
var img = index.locationImage;
var link = index.locationLink;
htmlcontent += '<div class="grid-item" id"' + key + '"><h4>' + name + '</h4><h5>' + state + '</h5>' + '<img src="' + img + '">' + '</div>' ;
});
$( '.main' ).append(htmlcontent);
$( '.grid-item' ).matchHeight();
});
});
HTML
<div class="main">
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="jquery.matchHeight.js"></script>
<script src="loadjson.js"></script>
CSS
img {
margin-top: 15px;
}
.main {
text-align: center;
}
.grid-item {
padding: 20px;
border: 1px solid black;
background-color: #eeeeee;
width: 275px;
float: left;
}