I am doing a college project and I would like to write my jQuery code following best practices. The project involves using the jQuery .getJSON
method to retrieve information from a json file. I have left out parts of the code so that it is more readable (however this is indicated in the comments).
The code shows two approaches I have come up with:
- In the first approach, I define a variable which contains HTML code and inserts this dynamically when making a call to the JSON file. I then do a small amount of DOM manipulation with this.
- In the second approach I don't need to define the variable at all. However, there is slightly more jQuery DOM manipulation when retrieving the information from the json file. also I'm not sure if what I have done is a bit 'hacky'.
Do you have any advice on which way would be better practice to do?
Option 1:
$(document).ready(function(){
//define a variable which contains html code that will be inserted dynamically depending on the contents of the json
var gift_love_template = '<span class="gift love-gift">' +
'<i class="fa fa-heart" aria-hidden="true"></i>' +
'<!--quantity of the gift will be dynamically inserted here-->' +
'</span>';
//the following code is inside the call to the JSON file:
$.each(profile.posts, function(i, post){
var quantity_love = post.gifts.love; //number of loves is stored in the gifts array within the post object.
if(quantity_love != 0){
var love_title = "" + quantity_love + " loves received"; //create a string for the title attribute
$("#" + post_id + " .gift-area").append(gift_love_template);
$("#" + post_id + " .love-gift").attr("title", love_title).append("(" + quantity_love + ")");
}
});
});
Option 2:
$(document).ready(function(){
//the following code is inside the call to the JSON file:
$.each(profile.posts, function(i, post){
var quantity_love = post.gifts.love; //number of loves is stored in the gifts array within the post object.
if(quantity_love != 0){
var love_title = "" + quantity_love + " loves received"; //create a string for the title attribute
$('<span><i class="fa fa-heart" aria-hidden="true"></i>(' + quantity_love + ')</span>').attr("class", "gift").attr("title", love_title).appendTo("#" + post_id + " .gift-area");
}
});
});