Reputation: 765
$("#paragraph").on("click", function(event){$("#paragraph").append(' Whoah! I didnt even know I could do that! I am a RAINBOW!')
event.preventDefault();})
I tried adding event.preventDefault() simply because I know that has to do with actions being permanent in some way or another. I honestly have no idea what it does. My problem is I want the text to only be added once no matter how many times the paragraph is clicked, currently, it keeps adding the text so that if you keep clicking it the text repeats.
Upvotes: 0
Views: 172
Reputation: 2800
Add a global. And you can use this
to reference your element.
let clicked = false;
$("#paragraph").on("click", function(event) {
if (!clicked) {
this.append(' Whoah! I didnt even know I could do that! I am a RAINBOW!');
clicked = true;
}
})
<p id="paragraph">Click</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Upvotes: -1
Reputation:
JQuery has a .one(..)
event that does exactly what you want. It attaches an event hander that fires only once.
$("#paragraph").one("click", function(event){$("#paragraph").append(' Whoah! I didnt even know I could do that! I am a RAINBOW!')});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="paragraph">I am the paragraph</p>
Upvotes: 4