Reputation: 57
I have written this function to assign line-height to elements with different heights.Is there any possible way of doing this using a for loop ?
$(".portfolio-image-overlay").each(function(){
"use strict";
var height = $(this).siblings("img").height();
var cheight = $(".item.active> a> img").height();
$(this).css({"line-height":height+"px"});
$(this).css({"line-height":cheight+"px"});
});
Upvotes: 2
Views: 22
Reputation: 4987
This is a for loop actually. The .each() function loops through the $(".portfolio-image-overlay") resultset.
You would be looking at something like this
var resultSet = $(".portfolio-image-overlay");
for (var i = 0; i < resultSet.length; i++) {
console.log(resultSet[i]);
}
Also, its smart to store the jQuery pointers in variables; Calling $(this) three times is less efficient than
var that = $(this);
and using that 3 times.
I see you're also doing that with the active item;
$(".portfolio-image-overlay").each(function(){
"use strict";
var height = $(this).siblings("img").height();
var cheight = $(".item.active> a> img").height();
$(this).css({"line-height":height+"px"});
$(this).css({"line-height":cheight+"px"});
});
This would be faster;
var activeItem = $(".item.active> a> img");
$(".portfolio-image-overlay").each(function(){
"use strict";
var that = $(this);
var height = that.siblings("img").height();
var cheight = activeItem.height();
that.css({"line-height":height+"px"});
that.css({"line-height":cheight+"px"}); //Don't know why you're doing this twice, maybe you've CSS animated it so i'll keep it there
});
EDIT:
Fastest would be as such;
var resultSet = $(".portfolio-image-overlay");
var cheight = $(".item.active> a> img").height();
for(var i = 0; i < resultSet.length; i ++){
var current = resultSet.eq(i);
var height = current.siblings("img").height();
current.css({"line-height":height+"px"}).css({"line-height":cheight+"px"});
}
Upvotes: 0
Reputation: 82251
Yes you can:
var portfolio = $(".portfolio-image-overlay");
for(var i=0;i < portfolio.length;i++){
var _this = portfolio.eq(i);
var height = _this.siblings("img").height();
var cheight = $(".item.active> a> img").height();
_this.css({"line-height":height+"px"});
_this.css({"line-height":cheight+"px"});
}
Upvotes: 1