Jimmy Oliver
Jimmy Oliver

Reputation: 11

Make height change from bottom to top

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

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206189

Nowadays you don't necessarily need jQuery.
You can achieve the desired by:

  • placing your element position: fixed; (or absolute) at a desired bottom coordinate (since you want to animate the height upwards)
  • listen (using JavaScript) for the Event.key (or Event.code) for "ArrowUp"
  • use Element.classList.toggle() to toggle a desired class (.is-active in this case)
  • don't forget to use Event.preventDefault() when pressing an arrow key to suppress the default behavior of the website scroll
  • animate using CSS 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

Related Questions