Reputation: 85
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!
Upvotes: 3
Views: 158
Reputation: 268324
I'm trying to understand the question. From what I can gather, you want only one paragraph to be selected at any given time, but the ability to add n paragraphs. If this is the case, I believe the following accomplishes this:
$( "#a" ).on( "click", "p", activateParagraph );
$( "#add" ).on( "click", addParagraph );
function addParagraph () {
$( "<p>", { text: 'Paragraph ' + $( "#a p" ).length++ } )
.appendTo( "#a" );
}
function activateParagraph () {
$( this )
.addClass( "on" )
.siblings( ".on" )
.removeClass( "on" );
}
Demo: http://jsbin.com/uziheg/2/edit
Upvotes: 0
Reputation: 76
You should use css to style your selected items. Each selected item can be given a css class "selected". On click, you can remove that class from all elements, then add the class to the element clicked on.
.selected { background-color: green; color: white; }
For the javascript:
var count = 1;
$("#add").on("click", function() {
$("#a").append('<p>Paragraph ' + count + '</p>');
count++;
});
$("#a").on("click", "p", function() {
$(".selected").removeClass("selected");
$(this).addClass("selected");
});
Upvotes: 2
Reputation: 318182
Just add a flag, like so:
$(document).ready(function(){
var count = 1, flag = false;
$("#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)") {
if (flag==false) {
$(this).css({"background-color":"green", "color":"white"});
flag=true;
}
} else {
$(this).css({"background-color":"white","color":""});
flag=false;
}
});
});
Upvotes: 1