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");
        });
    })
\$\endgroup\$
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")]);
        });
    });
});
\$\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\$ Dec 1 '14 at 4:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.