Andrej
Andrej

Reputation: 1736

button:active is not applied when form is submitted

I've got following situation.

A simple form with two fields and a submit button. Submit button was styled using :active pseudo-class and becomes red whenever pressed.

But it only works if button is clicked directly or the Space key is pressed (only in Chrome) when the button has focus.

However when the form is submitted using Enter key the button doesn't get its "active" state. Even if the button has focus and you press Enter it won't be styled.

Here an example:

document.getElementById("form1").addEventListener("submit", function(e) {

  e.preventDefault();

  document.getElementById("log").innerHTML += "Form submitted<br/>" ;
	  
  return false;
});

buttonClick = function() {
  document.getElementById("log").innerHTML += "Button clicked<br/>" ;
}
button {
  background: yellow;
}

button:active {
  background: red;
}
<form id="form1" >
  First name:<br>
  <input type="text" name="firstname" value="Mickey">
  <br><br>
  <button type="submit" onclick="buttonClick()">Submit</button>
  <br><br>
  <div id="log"></div>  
</form> 

One could say that's because actually the form is submitted without the button being pressed. But it's not true, you can submit the form any way you like the click event on the button itself will still fire.

Is this a bug or am I doing something wrong?

Note: <input type="submit"> and <button type="submit"></button> behave the same in this case

Upvotes: 0

Views: 2311

Answers (1)

Felix Haeberle
Felix Haeberle

Reputation: 1606

If you want to be sure that the active state/class is used try this:

button.active, button:active {
    // your code goes here
}

And try to add this in your buttonClick function (this is the button element) - and jQuery is used.

$(this).toggleClass('active');

I also recognized a issue that you can fire the submit button multiple times, try to disable the button on the first click if you don't want that with the following:

onclick="this.disabled = true;"

Upvotes: 1

Related Questions