3

For the sake of learning, I am making a login-registration system in HTML, CSS, and PHP. There would be different HTML text boxes and stuff.

What I want to achieve is when I write something in one text box, then take out my cursor and click on another textbox, I want to change the border color of the first text box to green.

I know how to change the border color through CSS but I want to do this only when such an event happens. Any help would be greatly appreciated.

Paulie_D
  • 107,962
  • 13
  • 142
  • 161
Ayush
  • 37
  • 1
  • 1
  • 6

3 Answers3

6

Attach blur event to the input.

document.querySelectorAll('input').forEach((input) => {
  input.addEventListener('blur', function() {
    this.classList.toggle('green', this.value.length > 0);
  });
});
.green {
    border: 2px solid green;
}
<input type="text">
<input type="text">
<button>Click Me</button>
random
  • 7,756
  • 3
  • 19
  • 25
0

You can add a class through Jquery and give the styles in CSS. It will also help you later when you try to add validations then you can just change class name for showing red borders to indicate errors.

You can also add a class when you are in focus to show your multiple state changes.

$(document).ready(function($) {
    $(".text").focus(function(){
       $(this).addClass("Yellow");
    }).blur(function(){
       $(this).addClass("success");
    })
});
V Mishra
  • 11
  • 1
  • 2
-1

here The code is :

input {
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  outline: none;
  height: 25px;
  width: 150px;
}

input:focus {
  border-color: green;
}
<input type="text" />