JQuery - How to prevent selection of the second paragraph when it is already selected ("clicked")

I have two functions: one creates paragraphs dynamically, and the other function selects ("changes the background color") and deselects ("changes to the default background color"). The problem is that I can select all paragraphs at once, and I want to be able to select one paragraph at a time, of course, after deselecting the already selected paragraph.

How to prevent selection / selection of another paragraph when it is already selected / highlighted?

Here you can check the full source code: 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 were clear enough, please help! You will be appreciated!

+3
source share
3

, :

$(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;
       }
  });
});

FIDDLE

+1

css . css "selected". , , .

.selected { background-color: green; color: white; }

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

http://jsfiddle.net/2QqmN/6/

+2

I am trying to understand the question. From what I can assemble, you want only one paragraph to be selected at any given time, but you can add n paragraphs. If so, I consider the following:

$( "#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

0
source

All Articles