This write-up will discuss:
Prerequisite: Create an HTML File
In HTML, add three “<button>” elements and assign each the “btn” and “nav-btn” classes:
<button class="btn nav-btn">About us</button>
<button class="btn nav-btn">Contact us</button>
Output
Now, let’s refers to the main subject of our post.
What is :active in CSS?
The “:active” pseudo-class indicates the element that is in an active state. In CSS, this class is specified with the elements to be styled as active, such as buttons, links, or more.
Style “nav-btn” Class
The “.nav-btn:active” is used to access the class “nav-btn”. This class is set with the “:active” pseudo-class and applied the following properties to show the button’s active state when clicked by the user:
background-color: blueviolet;
color: whitesmoke;
font-weight: bold;
}
Here:
- “background-color” changes the element’s background color.
- “color” specifies the font color.
- “font-weight” defines the font’s thickness.
Output
The above output verifies that the buttons’ styling changes when clicked by the users. However, they are not keeping their active state and fade away after the click.
How to Keep CSS :active Style After clicking a Button?
jQuery can be used to keep the active state of the buttons. For this purpose, add the styles within the class “nav-btn” and append the class “.active” with it:
background-color: blueviolet;
color: whitesmoke;
font-weight: bold;
}
jQuery Code
In the “<script>” tag add the following code:
$(".nav-btn").removeClass("active");
$(this).addClass("active");
});
Here is the description of the above code:
- The “$()” is the shortcut function of the “getElementById”.
- The “.nav-btn” is the class accessed through this function.
- The “.on(click, function()” denotes the function which will be triggered on the button click.
- The “$(“.nav-btn”).removeClass(“active”);” remove the styles from each button and implement the styles when the button is clicked.
- “$(this).addClass(“active”);” signifies that the styles must only be applied to that button that is currently clicked.
Output
That’s it! You have successfully learned how to maintain CSS “:active” style after a button click.
Conclusion
To keep the active state of a button, jQuery methods are used. For this purpose, first, access the button by using the “$()” method. Then, define the function to apply the active state styles on mouse click. Implement the event handler and the function. The function will first remove the styles from each button. Then, “$(this)” is used with the “:addClass()” to keep the active state of the button. This article has demonstrated the procedure for keeping CSS :active style after clicking a button.