Here is a variation of the code that can be used on multiple objects and with any selector, although it does not specifically rely on jQuery.
var onPositionChanged = function (selector,trigger, millis) {
if (millis == null) millis = 200;
setInterval(function(){
var o_s = jQuery(selector); // our jquery object
if (o_s.length < 1) return o_s;
for(var i = 0; i<o_s.length; i++)
{
var o = o_s.eq(i);
var lastPos = jQuery(o).attr("lastPos");
var lastOff = jQuery(o).attr("lastOff");
lastPos = ((lastPos == "" || lastPos == undefined) ? null : JSON.parse(lastPos));
lastOff = ((lastOff == "" || lastOff == undefined) ? null : JSON.parse(lastOff));
setTimeout(function (o) {
if (o == null || o.length < 1) return o; // abort if element is non existend eny more
if (lastPos == null) lastPos = o.position();
if (lastOff == null) lastOff = o.offset();
var newPos = o.position();
var newOff = o.offset();
if (lastPos.top != newPos.top || lastPos.left != newPos.left) {
jQuery(this).trigger('onPositionChanged', { lastPos: lastPos, newPos: newPos });
if (typeof (trigger) == "function") trigger(o,lastPos, newPos);
lastPos = o.position();
jQuery(o).attr("lastPos",JSON.stringify(lastPos));
}
if (lastOff.top != newOff.top || lastOff.left != newOff.left) {
jQuery(this).trigger('onOffsetChanged', { lastOff: lastOff, newOff: newOff});
if (typeof (trigger) == "function") trigger(o,lastOff, newOff);
lastOff= o.offset();
jQuery(o).attr("lastOff",JSON.stringify(lastOff));
}
}, millis,o);
}
},millis);
};
Example of how to use this:
jQuery(document).ready(function(){
onPositionChanged(".grid-item:not(.d-none)",function(object){
var left_percentage = parseInt(jQuery(object).position().left / jQuery(object).parent().width() * 100);
var parent_width = jQuery(object).parent().width();
var percentage_of_parent = parseInt(jQuery(object).width() / parent_width * 100);
if(left_percentage > 74 && percentage_of_parent >= 25
|| left_percentage > 66 && percentage_of_parent >= 33
|| left_percentage > 49 && percentage_of_parent >= 50)
{
jQuery(object).find(".card").css("margin-right","0px");
jQuery(object).parent().masonry('layout');
}
if(left_percentage < 1)
{
jQuery(object).find(".card").css("margin-left","0px");
jQuery(object).parent().masonry('layout');
}
});
});