Home > Back-end >  How to prevent content from moving down when error message is being shown?
How to prevent content from moving down when error message is being shown?

Time:11-30

In this code, when the input is empty and you press submit, an error message pops up, but it pushes the button down, I’m trying to prevent the button from getting pushed down. How can I do this?

This code is also available as a Side-by-side screenshots with horizontal lines added to compare heights. The  element has a lower vertical position after the error message appears.

CodePudding user response:

The .preventDefault() does its job, but you should place it into the if block. In the following snippet the form will only be submitted if the input field contains some text.

If the problem was the tiny vertical shift introduced by inserting the error message then this can be avoided by keeping it visible at all times with a minimum height and simply changing its .textContent accordingly.

const form = document.getElementById("form");
const input = document.getElementById("input");

form.addEventListener("submit", function (e) {
  const name = input.value;

  if (name === "") {
e.preventDefault();
addError("Input field cannot be empty");
  }
});

function addError(message) {
  const small = document.querySelector("small");
  small.classList.add("error");
  small.innerText = message;
}
* {
  box-sizing: border-box;
}

body {
  font-family: Arial, Helvetica, sans-serif;
}

.card {
  display: flex;
  min-height: 100vh;
  justify-content: center;
  align-items: center;
}

form {
  display: flex;
  flex-direction: column;
}

input {
  height: 2em;
  width: 15em;
}

.button {
  position: relative;
  top: 2em;
  width: fit-content;
  border: 2px solid;
  margin-top: 20px;
  margin: 0;
}

.button button {
  cursor: pointer;
}

small {
  font-style: italic;
  color: red;
  text-align: right;
  width: 15em;
  min-height: 20px;
  margin: 0;
}

.error small {
  display: block;
}
<div >
  <form action="somewhereelse.html" id="form">
    <h1>Please input your user name here</h1>
    <div ><input id="input" type="text" /></div>
    <small></small>
    <div >
      <button id="submit" type="submit">Submit</button>
    </div>
  </form>
</div>

CodePudding user response:

visibility:hidden hides the element, but it still takes up space in the layout. display:none removes the element from the document.

you can add following changes in CSS:

small {
  font-style: italic;
  color: red;
  text-align: right;
  width: 15em;
  visibility: hidden;
  height:10px;
  margin: 0;
}

.error small {
  visibility: visible;
}

and following Changes in JS

function addError(message) {
  const small = document.querySelector("small");
  small.classList.add("error");
  small.innerText = message;
  small.style.visibility= "visible";
}
  • Related