2
\$\begingroup\$

The script basically just appends the words based on the user's click/s on the textarea. I just need some help improving my code further using the .on("click", function{}) and making it shorter.

$(document).ready(function() {
 $("#add_user").on("click",function() {
 $("#textareaFixed").append("Lorem");
 });
 $("#add_disallow").on("click",function() {
 $("#textareaFixed").append("Ipsum");
 });
 $("#add_wild").on("click",function() {
 $("#textareaFixed").append("Dolor");
 });
 $("#add_comment").on("click",function() {
 $("#textareaFixed").append("Hey");
 });
 $("#add_bb").on("click",function() {
 $("#textareaFixed").append("World");
 });
 $("#add_gdrive").on("click",function() {
 $("#textareaFixed").append("Its Time");
 });
 $("#add_gimage").on("click",function() {
 $("#textareaFixed").append("To Move");
 });
 $("#add_gnews").on("click",function() {
 $("#textareaFixed").append("Again");
 });
 $("#add_bash").on("click",function() {
 $("#textareaFixed").append("Thats it");
 });
 })
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Dec 1, 2014 at 2:25
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

We can reduce duplication by using an object as a dictionary, and look up an output value based on an element's ID.

var messageMap = {
 "add_user": "Lorem",
 "add_disallow": "Ipsum",
 "add_wild": "Dolor",
 "add_comment": "Hey",
 "add_bb": "World",
 "add_gdrive": "Its Time",
 "add_gimage": "To Move",
 "add_gnews": "Again",
 "add_bash": "Thats it"
};
$(document).ready(function() {
 $.each(messageMap, function(key, value){
 $("#" + key).on("click",function() {
 $("#textareaFixed").append(messageMap[$(this).attr("id")]);
 });
 });
});
answered Dec 1, 2014 at 3:12
\$\endgroup\$
1
  • \$\begingroup\$ hmm makes sense.. I think this is a huge improvement on my code.. marking this as the answer thanks for the response mate :) \$\endgroup\$ Commented Dec 1, 2014 at 4:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.