0

How do I make it so that if I click outside a paragraph element then the background color is removed? Note I want to it to only be able to highlight one p at a time.

$('p').click(function() {
    $('p').removeClass('yellow');
    $(this).addClass('yellow');
});
.yellow {
    background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit tenetur sequi amet sit dolorem, nulla inventore quo cum ad distinctio aut nesciunt reprehenderit dolorum quidem animi unde aspernatur. Esse, eius!</p>
            <p>Deleniti vitae rerum eum saepe eaque tenetur libero, omnis nisi sapiente dicta est repellat, provident placeat quia inventore, at architecto quisquam, pariatur minus quam magni totam praesentium dignissimos. Incidunt, sequi.</p>
            <p>Fuga cupiditate consectetur, corporis architecto, doloremque impedit ullam quia praesentium voluptatibus molestiae dolor sint, odio amet atque culpa fugit blanditiis ea nam repellat necessitatibus. Aliquam voluptate fuga quo, omnis mollitia.</p>
        </div>
    </div>
</div>
Mohammad
  • 21,175
  • 15
  • 55
  • 84
ewcoder
  • 242
  • 3
  • 14
  • 2
    Possible duplicate of [How to detect a click outside an element?](http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element) – PeeHaa Jun 22 '16 at 21:20

3 Answers3

4

Here is what you want:

$('p').click(function(e) { 

$('p').removeClass('yellow'); //If there is any p with class yellow, it removes that
  $(e.target).closest('p').addClass('yellow'); //This find closest target when you click, in our case current paragraph(p)

});
$(document).click(function(e){ //Here is when you click in your entire document
  if($(e.target).closest('p').length==0) { // If click is not paragraph
     $('p').removeClass('yellow');  //It removes this class existed from any paragraph
    }
  

})
.yellow {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-md-12"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit tenetur sequi amet sit dolorem, nulla inventore quo cum ad distinctio aut nesciunt reprehenderit dolorum quidem animi unde aspernatur. Esse, eius!</p>
<p>Deleniti vitae rerum eum saepe eaque tenetur libero, omnis nisi sapiente dicta est repellat, provident placeat quia inventore, at architecto quisquam, pariatur minus quam magni totam praesentium dignissimos. Incidunt, sequi.</p>
<p>Fuga cupiditate consectetur, corporis architecto, doloremque impedit ullam quia praesentium voluptatibus molestiae dolor sint, odio amet atque culpa fugit blanditiis ea nam repellat necessitatibus. Aliquam voluptate fuga quo, omnis mollitia.</p></div>
  </div>
</div>
Teuta Koraqi
  • 1,898
  • 1
  • 10
  • 28
  • 1
    Could you possibly explain what is happening on each line of code in your jQuery? – ewcoder Jun 22 '16 at 21:40
  • 1
    I commented almost each line on my JQuery code. Take a look, I edited snippet! Hope you understand! :) – Teuta Koraqi Jun 22 '16 at 21:49
  • @TeutaKoraqi there's a caveat in your code that you did not considered - which will make your script **fail**, and that's: if any other unrelated element on the page also uses `event.stopPropagation()` in that case nothing will happen - cause `document` will never register that event - and will not *un-highlight* the paragraphs - even if `p` was not clicked. – Roko C. Buljan Jun 22 '16 at 21:51
  • @RokoC.Buljan, I did not think about it! Thanks for reminding me! I edited again my snippet. :) – Teuta Koraqi Jun 22 '16 at 22:02
  • @TeutaKoraqi even after your edit the problem still persists cause you bound your event to `document` > which never registered that event since some element used `event.stopPropagation();` You can easily test this by adding a random element that prevents the click to reach `document`. – Roko C. Buljan Jun 22 '16 at 22:04
1

Use this code

$("p").click(function (e){
    $("p").removeClass("yellow");
    $(this).addClass("yellow");
});

$(document).click(function (e){
    var element = $("p.yellow");

    if (!element.is(e.target) && element.has(e.target).length === 0)
        element.removeClass("yellow");
});
.yellow {
    background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="yellow">Text text text</p>
<p>Text text text</p>
<p>Text text text</p>
Mohammad
  • 21,175
  • 15
  • 55
  • 84
  • @mohammad I want to just have one paragraph selected in yellow at a time. Your method works but it is highlighting all paragraphs in yellow – ewcoder Jun 22 '16 at 21:28
  • @mohammad I have pasted in your code and now nothing changes if I click a p element – ewcoder Jun 22 '16 at 21:35
  • @ewcoder Excuse me for previous answer. I updated my asnwer related to question. – Mohammad Jun 22 '16 at 21:48
0

You can set a listener to the <body> and check if the click was onto a <p>:

$('body').click(function(event) {
    if(!$(event.target).is('p')) {
        $('p').removeClass('yellow');
    }
    else {
        $(event.target).addClass('yellow');
    }
});
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87