javascriptcssimage

JavaScript iterates through only the first four elements


So the thing is I want to display avatar with different sizes look a bit nice like that. If an image has Width <= Height then I will display it as my initial CSS, otherwise display it as a "landscape".

Problem is the first four images looks great, but I can't figure out why the last two are not picking up that landscape class (the sizes of the last two images are the same: 3104x1746 pixels). Can it be something wrong with JavaScript?

//@*Displaying list of images and names-----------------------*@
@foreach (var item in Model) {
    <div class="avatar-container">
        <div class="img-thumbnail">
            <img class="avatar img-thumbnail" src="@Href("~/Content/Avatars/",item.Name+".jpg")" />
        </div>  
        @Html.DisplayFor(modelItem => item.Name)  
    </div>
}   
//@*JavaScript------------------------------------------------*@  
<script>
    for (var i = 0; i < $(".avatar").length - 1; i++) {
        if ($(".avatar")[i].naturalWidth > $(".avatar")[i].naturalHeight) {
            $(".avatar").eq(i).addClass("landscape");
        }
    }
</script>
//@*CSS-------------------------------------------------------*@
div.avatar-container {
    display: inline-block;
    position: relative;
    width: 70px;
    height:70px;
    overflow: hidden;
}
div.img-thumbnail{
    width:100% !important;
    height:100%;
    background-color:#e1dada;
}
.img-thumbnail{
    padding:1px !important;
}
.avatar {
    position: absolute;
    top: 50%;
    left: 50%;
    height: 100%;
    width: auto;
    -webkit-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    -moz-transform: translate(-50%,-50%);
    -o-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}
.landscape{
    width:100%;
    height:auto;
}

Solution

  • i < $(".avatar").length - 1 is wrong as you are omitting the last item in the array. The array indexes are from 0 to length - 1, since you are doing i < length - 1 your loop executes from 0 to 2(length is 4 so i < 4-1) omitting the last element at index 3.

    You could use

    $(".avatar").each(function () {
        if (this.naturalWidth > this.naturalHeight) {
            $(this).addClass("landscape");
        }
    })
    

    To make your code work

    for (var i = 0; i < $(".avatar").length; i++) {
        //your code
    }