I have two functions, one creates paragraphs dynamically and the other function selects (“changes background color”) and deselects (“changes to default background color”). The problem I have is that I can select all paragraphs at the same time and I want to be able to select one paragraph at a time, of course, after deselecting the already selected paragraph.
How do I prevent another paragraph to be selected/highlighted when there is one already selected/highlighted?
You can check out the full source code here: http://jsfiddle.net/2QqmN/1/
jQuery code:
$(document).ready(function(){
var count = 1;
$("#add").on(
"click", function(){
$("#a").append('<p>Paragraph ' + count + '</p>');
count++;
});
$("#a").on("click", "p", function(){
var bg = $(this).css("background-color");
if(bg=="rgb(255, 255, 255)") {
$(this).css({"background-color":"green", "color":"white"});
}
else {
$(this).css({"background-color":"white","color":""});
}
});
});
If I was clear enough, please help!
You will be appreciated!
Just add a flag, like so:
FIDDLE