Why do i have to pre-style a input field in CSS before implementing that style by through Javascript?

Benard Manuh :

I am currently following a form validation tutorial in which i am creating a sign up form. I want the border of the input field and the icon to turn green if the information that is typed in by the user meets the input fields criteria and turn red if it does not, exactly like the picture below.

enter image description here

Here is the code for the "Username" input field.

.form-control.success input {
  border-color: #2ecc71;
}

.form-control .success i.fa-check-circle {
  visibility: visible;
  color: #2ecc71;
}
  <div class="form-control success" >
          <label for="username">Username</label>
          <input type="text" name="username"
          placeholder="Enter username..." id="username">
          <!-- Awesome fonts -->
          <i class="fas fa-check-circle"></i>
          <i class="fas fa-exclamation-circle"></i>

My instructor pre styled the input fields in CSS before he even worked on the Javascript file. My question is that why does it have to be pre styled in CSS, can't you just leave the input field normal and if the condition is met use Javascript to turn the input field green.

Morteza Sadri :

There are multiple ways to style form inputs conditions . The most basic is to change every style on tags that you want to change . I show you what exactly I mean .

function correctInput(elem) {
  elem.querySelector("input").style.borderColor = "#2ecc71";
  elem.querySelector("i.fa-check-circle").style.visibility= "visible";
  elem.querySelector("i.fa-check-circle").style.color = "#2ecc71";
}

In this way you are changing styles with javascript only . But the technique that your instructor used is much smarter . In this technique you use javascript and CSS together .

function correctInput(elem) {
  elem.setAttribute("class", "success");
}

Now you see the difference . In the CSS you will style your div block and children with every single condition that you want to have in your inputs . Then you only change the class name of the div block with javascript then CSS will do the rest for you .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=32030&siteId=1