Mr.Valentine
Mr.Valentine

Reputation: 63

convert JQuery code to Pure Javascript

I'm trying to rewrite the following JQuery to Pure Javascript.

I don't know why the code isn't working, but it isn't working. I'm guessing I'm doing wrong with the use of "focusing". Would anybody help me please?

JQuery(working)

$('.form-group input').on('focus blur', function (e) {
  $(this).parents('.form-group').toggleClass('active', (e.type === 'focus' || this.value.length > 0));
}).trigger('blur');

This is what I have so far(not working).

const inputs = document.querySelectorAll(".form-group input")
Array.from(inputs).forEach(input => {
  input.addEventListener("focusin", (e) => {
    const t = e.target as HTMLInputElement
    let formgroup = t.parentElement
    if(t.value.length > 0 ){
      formgroup.classList.toggle("onblur")
    }
  })
})

Here is the html tag.

    <form action="#" id="login-form">
        <div class="form-group">
          <label class="label-control">
            <span class="label-text">Email</span>
          </label>
          <input type="email" name="email" class="form-control" />
        </div>
        <div class="form-group">
          <label class="label-control">
            <span class="label-text">Password</span>
          </label> 
          <input type="password" name="password" class="form-control" />
        </div>
        <input type="submit" value="Login" class="btn" />
    </form>

Upvotes: 0

Views: 245

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

A couple of issues in regards to the jQuery code.

The class is named active and you are using onblur. The jquery code runs on both focus and blur.

const inputs = document.querySelectorAll(".form-group input");
const focusBlurHandler = (e) => {
    const t = e.target;
    let formgroup = t.parentElement;
    if(t.value.length > 0 ){
      formgroup.classList.toggle("active");
    }
};

Array.from(inputs).forEach(input => {
  input.addEventListener("focusin", focusBlurHandler);
  input.addEventListener("focusout", focusBlurHandler);
});
.active{background:lightgreen}
<form action="#" id="login-form">
        <div class="form-group">
          <label class="label-control">
            <span class="label-text">Email</span>
          </label>
          <input type="email" name="email" class="form-control" />
        </div>
        <div class="form-group">
          <label class="label-control">
            <span class="label-text">Password</span>
          </label> 
          <input type="password" name="password" class="form-control" />
        </div>
        <input type="submit" value="Login" class="btn" />
    </form>

Upvotes: 2

Related Questions