Brendan Jackson Brendan Jackson - 3 months ago 10
HTML Question

Jquery: $.each() returns value then ends

I have jQuery code to resize several Iframes based on the container they are in. When I did this without the

.each()
operator All of the iframes used the same div to base their size off of. With
.each()
the operator runs as evidenced by an alert but does not continue down the function.

Codepen: https://codepen.io/bjackson2016/pen/oLQopy?editors=0010

$(document).ready(function(){
function resize() {
var elements = $('.resize');
var eachElement = $.makeArray(elements);
alert(eachElement);
$.each(eachElement, function(index, value) {
alert(index + " " + value);
var multi = value.data('wfactor');
alert(multi);
var ratio = value.data('ratio');
alert(ratio);
var minX = value.data('minw');
alert(minX);
var minY = value.data('minh');
alert(minY);
var ruler = value.siblings('.widthTest');
alert(ruler);
var pWidth = ruler.width();
alert(pWidth);
var adjWidth = pWidth * multi;
alert(adjWidth);
var eHeight = (Math.round(ratio * adjWidth));
alert(eHeight);
var unadjHeight = Math.round(ratio * pWidth);
alert(unadjHeight);
var eWidth = (Math.round(adjWidth));
alert(eWidth);
if (eHeight < minY) {
$(this).height(minY);
alert('changed height');
} else {
value.height(eHeight);
alert('normal height');
}
if (eWidth < minX) {
value.css('width', pWidth).css('height', unadjHeight);
alert('changed width');
} else {
value.width(eWidth);
alert('kept width');
}
});
}

resize();

$(window).resize(function() {
resize();
});

});

Answer

The problem is that there is no value.data().

data() is a jQuery function, and iterating with $.each unwraps the elements, so you're trying to call data() on a native DOM node

$.each(eachElement, function(index, value) {

    // value is not a jQuery object here, you'd have to do

    var elem = $(value); // where you wrap it again.

});

Try instead

$(document).ready(function() {
    $(window).on('resize', resize).trigger('resize');

    function resize() {
        $('.resize').each(function(index, element) {
        var elem = $(element);

        var multi = elem.data('wfactor'),
            ratio = elem.data('ratio'),

            ... etc

        });
    }
});
Comments