Reputation: 2729
I want to retrieve width of paragraph element that is displayed only on hovering over input element.
test.html
<html>
<body>
<h1>Test</h1>
<div class="wrapper">
<input type="text">
<p id="spandiv">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p>
</div>
<style>
.wrapper > input {
display: block;
margin-left: auto;
margin-right: auto;
background-color: pink;
}
.wrapper > p {
text-align: center;
display: none;
}
.wrapper > input:hover + #spandiv {
background-color: grey;
display: block;
text-align: center;
padding: 5px;
color:white;
font-weight: normal;
overflow: hidden;
}
</style>
<script>
alert("width is"+document.getElementById('spandiv').offsetWidth);
</script>
</body>
</html>
for style .wrapper > p (see in the code above) if I apply display: block instead of display: block .I am able get width of p element. But I want to get width after hovering over input box and p element if I move out of input element.
Upvotes: 0
Views: 1530
Reputation: 3031
hide and show your element using opacity: 0
& opacity: 1
.
display: none
property is hide your element with its occupied space. that's why you are not getting width of your element.
alert("width is"+document.getElementById('spandiv').offsetWidth);
.wrapper > input {
display: block;
margin-left: auto;
margin-right: auto;
background-color: pink;
}
.wrapper > p {
text-align: center;
opacity: 0;
}
.wrapper > input:hover + #spandiv {
background-color: grey;
opacity: 1;
text-align: center;
padding: 5px;
color:white;
font-weight: normal;
overflow: hidden;
}
<h1>Test</h1>
<div class="wrapper">
<input type="text">
<p id="spandiv">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p>
</div>
Upvotes: 1
Reputation: 1005
The mouseleave event is fired after css has done it's work. You could reverse this in your JavaScript trigger by temporarily set the element to block level again and fetch it's width, then set the display property back to it's old status.
const mouseTarget = document.querySelector('input');
const spandiv = document.getElementById('spandiv');
mouseTarget.addEventListener('mouseleave', e => {
let displayValue = spandiv.style.display;
spandiv.style.display = 'block';
console.log("Width: "+spandiv.offsetWidth);
spandiv.style.display = displayValue;
});
See this JS bin.
Setting the opacity to 0 like KuldipKoradia suggests works too, but has a different behaviour when content is placed below your spandiv; A gap will always be visible when the spandiv is invisible. Depending on what you want, you can choose his solution or mine.
Upvotes: 2