\$\begingroup\$
\$\endgroup\$
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
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
-
\$\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\$Kim Oliveros– Kim Oliveros2014年12月01日 04:09:16 +00:00Commented Dec 1, 2014 at 4:09
default