Add active class to a div on javascript onclick event
Here we are applying a style to a simple div.
Steps to add a css class on click event
- Create a div with specific id (here id=”text”)
- on click on div call a method makeActive()
- Define a function makeActive() in side <script> tag.
- Inside makeActive() getElementById
- Get Elements classList and add class active.
- Use the innerHTML to change to element Text
Click to make Active
Add active class onclick javascript to HTML ul List to make menu
Here We have ul list elements to create horizontal menu on click on any element an active class is applied on it and if any one have already active class then remove it.
- create a ul menu with li items
- make menu display inline using css
- inside script tag select all anchor in menu class
- on click event find is there any active class in li
- if found then remove it
- add active class to clicked element.
Add active class to a div on Jquery onclick event
Here we have taken example of only a single div on click on div it will add an active class on div.
you can download or include Jquery from CDN
To achieve this follow these steps
- Define active css class
- Include Latest Jquery jquery.min.js file to your html
- Create a div with id text.
- Write Jquery code inside script tag.
- Check for document ready state if ready then
- write click function for #text
- add a class using jquery addClass()
- Change the div content using Jquery text().
Click to make Active
Add active class onclick JQuery to HTML ul List to make menu
As we already seen how to add a active class in HTML List.
The same work we will do with JQuery.
JQuery provides easy way to add and remove css class in any element
- Create a simple HTML unordered list
- Style list to make inline and provide margin
- define a active style in css
- Include Jquery latest jquery.min.js file
- Write Jquery event that will work on document ready
- On click on anchor tag inside li first remove all active class from li then add active class in parent li of anchor tag.
Jquery provides addClass() and removeClass() to add and remove any css class.
You can learn how to access parent class id in JQuery
Add Hover effect in HTML menu using JQuery hover()
To add hover effect we used below code.
This will add and remove css class on hover.
$( "a" ).hover(function() { $(this).parent("li").addClass("hover"); }, function() { $(".menu li").removeClass("hover"); });