Auguste Auguste - 4 months ago 50
jQuery Question

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');
});
});

Answer

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.

Comments