I want to check the height of an element every time the site changes, because of a viewport resize or a click event.
At the moment I'm using the following code:
jQuery(function ($) {
var height = document.getElementById("head").offsetHeight;
var x = document.getElementsByClassName("dropdown-menu");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.top = height + 'px';
}
});
It's possible that the height of "head" changes. So I need to check the actual height if there are any changes at the site/viewport.
Is there a way to do so?
You can use onresize event listener of javascript
var header= document.getElementById("head")
header.addEventListener('onresize', function(){
// do your code here
});
You can check on window resize
$( window ).resize(function() {
//check element height
});
var element = document.getElementById("head"),
height;
function eventHandler () {
height = element.offsetHeight;
console.log(height);
// rest of your code
}
window.addEventListener('resize', eventHandler)
element.addEventListener('click', eventHandler)
You can bind two different event listeners and pass the same function as a callback if you want to share code logic and reduce redundancy.
My solution:
$( window ).ready(function() {
var height = document.getElementById("head").offsetHeight;
var x = document.getElementsByClassName("dropdown-menu");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.top = height + 'px';
}
});
$( window ).click(function() {
setTimeout(function() {
var height = document.getElementById("head").offsetHeight;
var x = document.getElementsByClassName("dropdown-menu");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.top = height + 'px';
}
}, 500);
});
$( window ).resize(function() {
var height = document.getElementById("head").offsetHeight;
var x = document.getElementsByClassName("dropdown-menu");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.top = height + 'px';
}
});
The timeout is for the correct height after the click and an animation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.