Reputation: 11
I have a red div which increases height from top to bottom on key down and decreases on key up I want the height to change from bottom to top instead of top to bottom. style:
.load { width: 550px; height: 0; background-color: red; position: absolute; top: 50px; z-index: -1; transform: rotate(180deg); } html:
<div class="load"></div>
jquery: `$(document).ready(function() { var animating = false; var isExpanded = false;
$(document).on('keydown keyup', function(e) {
if (e.keyCode === 38) { // Check if up arrow key is pressed or released
if (e.type === 'keydown' && !animating && !isExpanded) { // If key is pressed and not already expanded
animating = true;
$(".load").stop().animate({height: "510px"}, 2000, function() {
animating = false;
isExpanded = true;
});
} else if (e.type === 'keyup' && (isExpanded || animating)) { // If key is released and either expanded or currently animating
$(".load").stop().animate({height: "0"}, 2000, function() {
animating = false;
isExpanded = false;
});
}
}
});
});`
Would help a lot thanks.
Upvotes: 1
Views: 52
Reputation: 206189
Nowadays you don't necessarily need jQuery.
You can achieve the desired by:
position: fixed;
(or absolute
) at a desired bottom
coordinate (since you want to animate the height upwards).is-active
in this case)transition
const elLoad = document.querySelector("#load");
const handleLoad = (evt) => {
if (evt.key !== "ArrowUp") return; // Do nothing. Not our key.
evt.preventDefault(); // prevent default page scroll on arrow key
elLoad.classList.toggle("is-active", evt.type === "keydown");
};
;["keydown","keyup"].forEach(evType => addEventListener(evType, handleLoad));
/*QuickReset*/ * { margin: 0; box-sizing: border-box; }
#load {
position: fixed;
bottom: 0dvh;
width: 100%;
height: 0px;
background: red;
transition: height 2s;
&.is-active {
height: 50vh;
}
}
Click this iframe and hold the ArrowUp key
<div id="load"></div>
Less code, more performant, and the styling is offloaded completely where it belongs, and that's CSS.
Upvotes: 0