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'); }); });
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.
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.
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.
To add the CSS classes to an element we use addClass() method, and to remove the CSS classes we use removeClass() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With