Adam
Adam

Reputation: 832

jQuery applying height from data attribute

I am trying to apply the height from the data attributes onto the divs, this only works for the first one as the second div gets the same height from the first element. Does anyone know of a way around this do I need to run it as an each function for example?

https://jsfiddle.net/y45rgsza/

var $elements = {
   button: $('.js-show-more'),
   container: $('.js-readmore-container'),
   blockheight: $('.js-block-height')
};


var maxheight = $elements.container.height();
var height = $elements.blockheight.data('height');

if (maxheight > 5) {
   $elements.blockheight.css("height", height);
}

Upvotes: 0

Views: 846

Answers (5)

Jasper
Jasper

Reputation: 11

Use each function to check each and every container to get data attributes and apply inside blockheight.

Here is new working code,

var $elements = {
button: $('.js-show-more'),
container: $('.js-readmore-container'),
blockheight: $('.js-block-height')};
$($elements.container).each(function(){
var maxheight = $(this).height();
var height = $(this).find($elements.blockheight).data('height');
if (maxheight > 5) {
$(this).find($elements.blockheight).css("height", height);
}});

https://jsfiddle.net/y45rgsza/6/

Upvotes: 0

Akshat G
Akshat G

Reputation: 214

Simple get all elements with class js-block-height and iterate :

var elements=$(".js-block-height");
elements.each(function(){
   $(this).css("height",$(this).data("height")); 
});

Fiddle : https://jsfiddle.net/y45rgsza/5/

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388366

You need to iterate and set

var $elements = {
    button: $('.js-show-more'),
    container: $('.js-readmore-container')
};

$elements.container.height(function (i, height) {
    var bheight = $(this).find('.js-block-height').data('height');
    return bheight < height ? bheight : height
})

Demo: Fiddle

Upvotes: 0

Jai
Jai

Reputation: 74738

You can make use of .css(prop, callback) like this:

$elements.blockheight.css("height", function(){
    return $(this).data('height') //return the current elements data attribute value.
});

Fiddle

Upvotes: 1

lem2802
lem2802

Reputation: 1162

Use:

$elements.blockheight.height(height);

Upvotes: 0

Related Questions