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
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.
**This can be achived easily using two different ways:**
1)We can also do this by using addClass and removeClass of Jquery
2)Toggle class of jQuery
**1)First Way**
$(documnet.ready(function(){
$('#dvId').click(function(){
$('#dvId').removeClass('active class or your class name which you want to remove').addClass('active class or your class name which you want to add');
});
});
**2) Second Way**
i) Here we need to add the class which we want to show while page get loads.
ii)after clicking on div we we will toggle class i.e. the class is added while loading page gets removed and class which we provide in toggleClss gets added :)
<div id="dvId" class="ActiveClassname ">
</div
$(documnet.ready(function(){
$('#dvId').click(function(){
$('#dvId').toggleClass('ActiveClassname InActiveClassName');
});
});
Enjoy.....:)
If you any doubt free to ask any time...
You can use a single line to add and remove class on a div. Please remove a class first to add a new class.
$('div').on('click',function(){
$('div').removeClass('active').addClass('active');
});
I had to transform the divs to list items otherwise all my divs would get that class and only the generated ones should get it Thanks everyone, I love this site and the helpful people on it !!!! You can follow the newbie school project at http://low-budgetwebservice.be/project/webbuilder.html suggestions are always welcome :). So this worked for me:
/* Add Class Heading*/
$(document).ready(function() {
$( document ).on( 'click', 'ul#items li', function () {
$('ul#items li').removeClass('active');
$(this).addClass('active');
});
});
It's all about the selector. You can change your code to be something like this:
<div class="formbuilder">
<div class="active">Heading</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
Then use this javascript:
$(document).ready(function () {
$('.formbuilder div').on('click', function () {
$('.formbuilder div').removeClass('active');
$(this).addClass('active');
});
});
The example in a working jsfiddle
See this api about the selector I used: http://api.jquery.com/descendant-selector/
In this mode you can find all element which has class active and remove it
try this
$(document).ready(function() {
$(this.attr('id')).click(function () {
$(document).find('.active').removeClass('active');
var DivId = $(this).attr('id');
alert(DivId);
$(this).addClass('active');
});
});