Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery addclass to selected div, remove class if another div is selected

I'm making a formbuilder, I would like to change the appearance of for example a heading div. When clicked it should get a border but when another dynamically generated div is clicked the class should be removed and the second clicked div has to get the .active class.

How can I do this with generated divs?

Anyway I found something that works but I still need the If another div is selected, previous div.removeclass and selected div.addclass

This works:

/* Add Class */ $(document).ready(function() {     $( document ).on( 'click', '.HeadingDiv', function () { /* This '.HeadingDiv' could be anything, I need something dynamic here */         $('.HeadingDiv').removeClass('active'); /* This '.HeadingDiv' could be anything, I need something dynamic here */         $(this).addClass('active');     }); }); 
like image 434
Auguste Avatar asked Sep 18 '13 16:09

Auguste


People also ask

How to add and remove class in div using jQuery?

How to use addClass() and removeClass() to remove one class name, and add a new class name. Using a function to remove a class from the selected elements. How to remove several class names from the selected elements.

What does addClass do in jQuery?

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

How to add class using jQuery in div tag?

To add a new class, we use jQuery addClass() method. The addClass() method is used to add more classes and their attributes to each selected element. It can also be used to change the property of the selected element.

How do you remove a class in CSS?

To add the CSS classes to an element we use addClass() method, and to remove the CSS classes we use removeClass() method.


1 Answers

Are you looking something like this short and effective:

http://jsfiddle.net/XBfMV/

$('div').on('click',function(){   $('div').removeClass('active');   $(this).addClass('active'); }); 

you can simply add a general class 'active' for selected div. when a div is clicked, remove the 'active' class, and add it to the clicked div.

like image 138
Caner Akdeniz Avatar answered Sep 28 '22 17:09

Caner Akdeniz