CameronK
CameronK

Reputation: 3

Can I get an attribute of a div after hover without initiating the hover itself?

Is it possible to get the height of a div with unknown content after hover without initiating the hover itself?

Could jquery help here?

.content-container{
  width:20%;
  border:1px solid #000;
}

.content-container:hover{
  width:100%;
}
<div class="content-container">Some content that can be anything of any length</div>

Upvotes: 0

Views: 39

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

You have to do something to make the rule apply, take the measurement, then remove that something. One easy way is to update the rule to also apply with a class, then add the class, measure, remove the class:

var container = $(".content-container");
var unexpanded = container.height();
console.log("height when unexpanded: " + unexpanded);
container.addClass("expand");
var expanded = container.height();
container.removeClass("expand");
console.log("height when expanded: " + expanded);
.content-container{
  width:20%;
  border:1px solid #000;
}

.content-container:hover, .content-container.expand {
  width:100%;
}
<div class="content-container">Some content that can be anything of any length</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

That measures the first/only .content-container. If you have multiple, you'll need an each loop:

$(".content-container").each(function() {
    var container = $(this);
    // ...
});

Upvotes: 1

Related Questions