.Animate() on dynamically generated content - javascript

I am creating a website where I append progress-bar to div from JSON file.
Everything is working fine, but I can't figure out how to animate all progress-bar with their own value.
These values are loaded from the JSON file and I am only able to animate them all to one value not to their own one.
Code :
$.getJSON( "skills.json", function(data){
Skills = data;
$.each(Skills, function (title, val) {
var markup = "<div class='progress-item'>";
markup += "<span class='progress-title'>" + val.title + "</span>";
markup += "<div class='progress'>";
markup += "<div class='progress-bar'" + "style=width:" + val.value + "%" + ">" + "<span class='progress-percent'>" + val.value + "%" + "</span></div>";
markup += "</div>";
markup += "</div>";
$('.progress-wrapper').append(markup);
});
});
So this generates 3 progress-bar cause I have 3 values in my JSON file.
I tried something like :
$(".progress-bar").animate({width: val.value +"%"});
But it change the width of all my progress-bar even if they got all different in the JSON object.
JSON file :
[{
"title": "Skill 1",
"description": "Skill 1 description",
"value": 100
},
{
"title": "Skill 2",
"description": "Skill 2 description",
"value": 50
}
]
Thanks in advance for the help

Related

Simplifying a messy jQuery function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 10 months ago.
Improve this question
JS newb here. I'm incorporating the code below into a backstretch slider, with the aim of including small text arrays with each rotation of a carousel. It's all working as planned, only it's not very clean code at all. I'm just wondering if someone knows how to go about neatening this up? Thanks a lot!
jQuery(document).ready(function ($) {
var items = [{
img: "/i/photos/Gallery/home/010.jpg",
name: "Name 1",
title: "Title 1",
desc: "Description 1.",
caption: "Read More",
link: "#"
},
{
img: "/i/photos/Gallery/home/020.jpg",
name2: "Name 1",
title2: "Title 1",
desc2: "Description 1.",
caption2: "Read More",
link2: "#"
},
{
img: "/i/photos/Gallery/home/030.jpg",
name3: "Name 1",
title3: "Title 1",
desc3: "Description 1.",
caption3: "Read More",
link3: "#"
}
];
var options = {
fade: 800,
duration: 7000
};
var images = $.map(items, function (i) {
return i.img;
});
var slideshow = $("#slider").backstretch(images, options);
$(window).on("backstretch.show", function (e, instance) {
var theName = items[instance.index].name;
var theTitle = items[instance.index].title;
var theDesc = items[instance.index].desc;
var theCaption = items[instance.index].caption;
var theLink = items[instance.index].link;
var theName2 = items[instance.index].name2;
var theTitle2 = items[instance.index].title2;
var theDesc2 = items[instance.index].desc2;
var theCaption2 = items[instance.index].caption2;
var theLink2 = items[instance.index].link2;
var theName3 = items[instance.index].name3;
var theTitle3 = items[instance.index].title3;
var theDesc3 = items[instance.index].desc3;
var theCaption3 = items[instance.index].caption3;
var theLink3 = items[instance.index].link3;
if (theLink) {
$(".backstretch-caption").html(
'<h1 class="bs-name">' + theName + '</h1>' +
'<h2 class="bs-title">' + theTitle + '</h2>' +
'<p class="bs-desc">' + theDesc + '</p>' +
'<a class="bs-link" href="' + theLink + '">' + theCaption + '</a>')
.show();
}
if (theLink2) {
$(".backstretch-caption").html(
'<h1 class="bs-name">' + theName2 + '</h1>' +
'<h2 class="bs-title">' + theTitle2 + '</h2>' +
'<p class="bs-desc">' + theDesc2 + '</p>' +
'<a class="bs-link" href="' + theLink2 + '">' + theCaption2 + '</a>')
.show();
}
if (theLink3) {
$(".backstretch-caption").html(
'<h1 class="bs-name">' + theName3 + '</h1>' +
'<h2 class="bs-title">' + theTitle3 + '</h2>' +
'<p class="bs-desc">' + theDesc3 + '</p>' +
'<a class="bs-link" href="' + theLink3 + '">' + theCaption3 + '</a>')
.show();
}
});
});
The most important change to make here is to remove the incremental property names in the objects in your array; use the same property name in each object. Then your code dealing with that array can be simplified as the property names are static.
You can also make the syntax a little less verbose by storing a reference to items[instance.index] in a variable to reuse, and also by using template literals to build your HTML. The latter could be made even more simple by including the HTML in the page on load, and hiding/updating/showing the relevant text labels as necessary - I'll leave that as an exercise for the OP to implement if desired though.
var items = [
{ img: "/i/photos/Gallery/home/010.jpg", name: "Name 1", title: "Title 1", desc: "Description 1.", caption: "Read More", link: "#" },
{ img: "/i/photos/Gallery/home/020.jpg", name: "Name 1", title: "Title 1", desc: "Description 1.", caption: "Read More", link: "#" },
{ img: "/i/photos/Gallery/home/030.jpg", name: "Name 1", title: "Title 1", desc: "Description 1.", caption: "Read More", link: "#" }
];
jQuery($ => {
var images = items.map(item => item.img);
var slideshow = $("#slider").backstretch(images, {
fade: 800,
duration: 7000
});
$(window).on("backstretch.show", function (e, instance) {
let item = items[instance.index];
if (item.link) {
$(".backstretch-caption").html(`
<h1 class="bs-name">${item.name}</h1>
<h2 class="bs-title">${item.title}</h2>
<p class="bs-desc">${item.desc}</p>
<a class="bs-link" href="${item.link}">${item.caption}</a>`)
.show();
}
});
});
Finally, be wary of using the Backstretch library. It hasn't had a meaningful update since 2017 and seems very outdated. In fact, it's now possible to do what that library does using CSS, such as using vw/vh units for fonts and various other techniques for background imagery.

How to paginate the JSON data at client side without using Bootstrap?

Solution is in this JSFiddle: https://jsfiddle.net/rinku16/mpo7xyjk/17/
When the user click on Filter Search and JSON is downloaded on client side according to the search condition and my pagination JS function partition the rows according to number of rows per page and accordingly make numeral navigation button between previous and next buttons.
I have problem of synchronization of navigation button for pages and previous/Next Button.
My Problem as follows
For example: Initially on search click it displays only table header but if user presses next button it displays (10-19) 10 records continuing (skipped) after 0-9 of previous rows but if user click 0 navigation button (between previous and next buttons) but it displays (0-1-2) 3 rows (but it should display 0-9 rows) and when click on 1 button it should display (10-19) but it displaying (3-4-5).
I have updated the code in this JSFiddle link (https://jsfiddle.net/rinku16/hn3t9gz6/33/) but it is not working properly.
I am trying to build a logic. You can check all logic at the link. I am not able to do following task.
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<div class="row">
<div class="col">
<div>
Pagination Div
<div id="pagination"></div>
</div>
</div>
</div>
<div class="row" style="overflow-x:auto;">
<div class="col">
<div>
Records Div
<div id="filterRecords"></div>
</div>
</div>
</div>
</body>
</html>
Logic for client side:
// This is script to load table based on filter section
$(document).ready(function() {
userDetails = [{
"Lead_Id": "66",
"FirstName": "John",
"LastName": "Doe",
"Company": "Google",
"Website": "www.google.com",
"Designation": "Manager",
"Linkedin": "www.linkedin.com\/john-doe",
"Email": "johndoe#google.com",
"Phone": "5125501553",
"State": "Delaware",
"Country": "USA",
"TechArea": "Cloud computing",
"FirmType": "Corporate",
"FirmSize": "Less than 10",
"LastContactDate": "2020-02-03",
"NextContactDate": "2020-02-29",
"LeadDescription": "This is lead description testing",
"OwnerNotes": null,
"SetReminder": "2020-02-29",
"AdminNotes": "This is admin notes testing",
"LeadStatus": "Planned",
"LeadAddedBy": "18",
"LeadAddedOn": "2020-02-03 16:28:26",
"LeadUpdatedBy": null,
"LeadUpdatedOn": null
}, {
"Lead_Id": "67",
"FirstName": "Tohn",
"LastName": "Doe",
"Company": "Microsoft",
"Website": "www.microsoft.com",
"Designation": "Manager",
"Linkedin": "www.linkedin.com\/tohn-doe",
"Email": "tohn#microsoft.com",
"Phone": "123456",
"State": "California",
"Country": "USA",
"TechArea": "Computer Networks",
"FirmType": "Corporate",
"FirmSize": "Less than 10",
"LastContactDate": "2020-03-05",
"NextContactDate": "2020-03-07",
"LeadDescription": "This is test lead description",
"OwnerNotes": null,
"SetReminder": "2020-03-11",
"AdminNotes": "This is testing admin notes",
"LeadStatus": "Planned",
"LeadAddedBy": "18",
"LeadAddedOn": "2020-03-05 10:47:21",
"LeadUpdatedBy": null,
"LeadUpdatedOn": null
}];
//More JSON object you can get on jsfiddle link
$("#filterRecords").empty();
var result = $.parseJSON(userDetails);
//###########################################
// Pagination code start
//###########################################
$("#pagination").attr('style', 'display:block;');
$('#pagination').html('<div class="row"><div class="col"><button class="col PreviousButton" id="PreValue"><i class="ion-skip-backward"></i> Previous</button></div> <div id="nav-numbers" class="col nav"></div> <div class="col"><button class="col NextButton" id="nextValue">Next <i class="ion-skip-forward"></i></button></div></div>');
paginate_json_data(result)
$("#filterRecords").html(table);
//###########################################
// Pagination code end
//###########################################
});
function paginate_json_data(userDetails) {
var table = '';
table = $("<table></table>");
table.append('<thead><th>#</th><th>Name</th><th>Company</th><th>Website</th><th>Designation</th><th>Linkedin</th><th>Email</th><th>Phone</th><th>State</th><th>Country</th><th>TechArea</th><th>Firm Type</th><th>Firm Size</th><th>Last Contact Date</th><th>Next Contact Date</th><th>Lead Description</th><th>Owner Notes</th><th>Reminder Date</th><th>Admin Notes</th><th>Lead Status</th><th>Lead Added By</th><th>Lead Added On</th><th>Lead Updated By</th><th>Lead Updated On</th></thead><br>');
table.append('<tbody id="myTable"></tbody>');
userDetails = userDetails
$('#pagination').append('<p1>Total number of rows fetched: ' + userDetails.length + '</p1>');
var max_size = userDetails.length;
var sta = 0;
var elements_per_page = 10;
// var elements_per_page = rows_per_page;
var limit = elements_per_page;
goFun(sta, limit);
function goFun(sta, limit) {
// console.log(sta,limit);
for (var i = sta; i < limit; i++) {
var tab = '<tr><td>' + i + "\n" + '</td><td>' + "<a target='_blank' href=./lead/index.html?lead_id=" + userDetails[i].Lead_Id + " </a>" + userDetails[i].FirstName + ' ' + userDetails[i].LastName + "\n" + '</td><td>' + userDetails[i].Company + "\n" + '</td><td>' + userDetails[i].Website + "\n" + '</td><td>' + userDetails[i].Designation + "\n" + '</td><td>' + userDetails[i].Linkedin + "\n" + '</td><td>' + "" + userDetails[i].Email + "" + "\n" + '</td><td>' + userDetails[i].Phone + "\n" + '</td><td>' + userDetails[i].State + "\n" + '</td><td>' + userDetails[i].Country + "\n" + '</td><td>' + userDetails[i].TechArea + "\n" + '</td><td>' + userDetails[i].FirmType + "\n" + '</td><td>' + userDetails[i].FirmSize + "\n" + '</td><td>' + userDetails[i].LastContactDate + "\n" + '</td><td>' + userDetails[i].NextContactDate + "\n" + '</td><td>' + userDetails[i].LeadDescription + "\n" + '</td><td>' + userDetails[i].OwnerNotes + "\n" + '</td><td>' + userDetails[i].SetReminder + "\n" + '</td><td>' + userDetails[i].AdminNotes + "\n" + '</td><td>' + userDetails[i].LeadStatus + "\n" + '</td><td>' + "<a target='_blank' href=./account/index.html?user_id=" + userDetails[i].LeadAddedBy + " </a>" + userDetails[i].LeadAddedBy + "\n" + '</td><td>' + userDetails[i].LeadAddedOn + "\n" + '</td><td>' + userDetails[i].LeadUpdatedBy + "\n" + '</td><td>' + userDetails[i].LeadUpdatedOn + "\n" + '</td></tr>';
$('#myTable').append(tab)
}
}
$('#nextValue').click(function() {
var next = limit;
if (max_size >= next) {
def = limit + elements_per_page;
limit = def
$('#myTable').empty();
if (limit > max_size) {
def = max_size;
}
goFun(next, def);
}
});
$('#PreValue').click(function() {
var pre = limit - (2 * elements_per_page);
if (pre >= 0) {
limit = limit - elements_per_page;
$('#myTable').empty();
goFun(pre, limit);
}
});
var number = Math.round(userDetails.length / elements_per_page);
for (i = 0; i <= number; i++) {
$('.nav').append('<button class="nav-numbers btn" id=' + i + '>' + i + '</button>');
}
$('.nav button').click(function() {
var start = $(this).text();
$('#myTable').empty();
limit = 3 * (parseInt(start) + 1) > max_size ? max_size : 3 * (parseInt(start) + 1)
goFun(start * 3, limit);
});
}
I want to do two things using paginate.
Partition the number of rows example: JSON has 32 rows then rows view per page 10 then i have buttons as 1 (10 row), [2] (10 rows),[3] (10 rows), [4] (2 rows) {I have written code for this in link}
Move the focus from one button to next button on (next button click) 1 -> [2] -> [3] -> [4]) {I have not written code for this as it need CSS changes using button id(1->[2]->[3]->[4])}
The problem is button click previous and next are not synchronized with focused buttons (1->[2]->[3]->[4]).
Screenshot of my work until now.
Please correct my code.
If understand it right, if you click the button 1,2 or 3 it shows only the next 3 new but should show the next 10 new.
then change the following:
change the "3" to "10" in your code
$('.nav button').click(function() {
var start = $(this).text();
$('#myTable').empty();
limit = 10 * (parseInt(start) + 1) > max_size ? max_size : 10 * (parseInt(start) + 1)
goFun(start * 10, limit);
});
EDIT:
to start directly with result, you can execute the first button like
$('.nav button')[0].click()
only put this at the end of your code
see fiddle
Take a look on that fork (https://jsfiddle.net/Kyrylo/2hbxmove/)
Instead focus I use button's disable/enable, but idea the same.
// keep in scope var current - ref to current page
// on nav btn click, prev, next
// remove disabled attr from current btn
$('#' + current).removeAttr('disabled');
// update current value, line below from onPrevClick handler
current = Math.max(current - 1 , 0);
// disable new current
$('#' + current).attr('disabled', 'disabled');

How to parse json with javascript/jquery if content matches string

I currently have a json file of people taking part in a series of charity events in the following format:
[
{
"FirstName": "Anushka",
"Country": "UK",
"Day": "13/10/2017"
},
{
"FirstName": "Alessandra",
"Country": "IT",
"Day": "16/10/2017"
},
{
"FirstName": "Clare",
"Country": "US",
"Day": "13/10/2017"
}
]
I want to build a simple HTML list using this data, so that under each date, the name and country are displayed like:
<div id="13102017">
<h1>13/10/2017</h1>
<div class="col-sm-4"><p>Anushka, UK</p></div>
<div class="col-sm-4"><p>Clare, US</p></div>
</div>
<div id="16102017">
<h1>16/10/2017</h1>
<div class="col-sm-4"><p>Alessandra, IT</p></div>
</div>
I've new to JSON and so far I have figured out how to get Name and Country onto the page, but I cannot figure out how to use an if statement to only output if date = 13/10/2017 for example.
Here's what I've got so far:
$( document ).ready(function() {
$.getJSON("URL_HERE", function(data) {
$.each(data, function(i, item) {
$('#13102017').append('<div class="col-sm-4"><p>' + item.FirstName + ", " + item.Country + '</p></div>');
});
});
});
Obviously the above is currently just outputting every single name into the #13102017 section. I know I probably need an IF in there somewhere but I'm otherwise stumped. Any pointers would be much appreciated!
On each loop, check first if the date div exists, and if not, create it. Then append the info to that div...
$.getJSON("URL_HERE",function(data) {
$.each(data, function(i,item) {
var dateId = item.Day.replace(/\//g,'');
if (!$('div#'+dateId).length)
$('body').append('<div id="'+dateId+'"><h1>'+item.Day+'</h1></div>');
$('div#'+dateId).append('<div class="col-sm-4"><p>' + item.FirstName + ", " + item.Country + '</p></div>');
});
});
For array loops, I personally prefer to use for (is faster than jquery each)...
$.getJSON("URL_HERE",function(data) {
for (var i=0, l=data.length; i<l; i++) {
var item = data[i],
dateId = item.Day.replace(/\//g,'');
if (!$('div#'+dateId).length)
$('body').append('<div id="'+dateId+'"><h1>'+item.Day+'</h1></div>');
$('div#'+dateId).append('<div class="col-sm-4"><p>' + item.FirstName + ", " + item.Country + '</p></div>');
}
});
NOTE: I'm adding the date div's to the body, just change $('body') to the container where you want to put them in your page.
I would suggest you to create the whole html and then set it as html.
var data = [{
"FirstName": "Anushka",
"Country": "UK",
"Day": "13/10/2017"
},
{
"FirstName": "Alessandra",
"Country": "IT",
"Day": "16/10/2017"
},
{
"FirstName": "Clare",
"Country": "US",
"Day": "13/10/2017"
}
];
$(function() {
// You can have this inside $.getJSON
var _html = "";
data.forEach(function(item) {
_html += '<div id="' + item.Day.replace(/\//g, "") + '">' +
'<h1>' + item.Day + '</h1>' +
'<div class="col-sm-4"><p>' + item.FirstName + ", " + item.Country + '</p></div>' +
'</div>';
});
$("#container").html(_html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
but I cannot figure out how to use an if statement to only output if
date = 13/10/2017
Simply check if item.Day == "13102017"
$( document ).ready(function() {
$.getJSON("URL_HERE", function(data) {
$.each(data, function(i, item) {
if ( item.Day == "13102017" )
{
var id = item.Day.replace( /\D/g, "" );
var html = '<div id="' id '">';
html += '<h1>' + item.Day + '</h1>';
html += '<div class="col-sm-4"><p>' + item.FirstName + '</p></div>';
html += '<div class="col-sm-4"><p>' + item.Country + '</p></div>';
html += '</div>';
$(body).append( html );
}
});
});
});

Bootstrap jQuery Calendar

I've found an awesome open source calendar at http://bootstrap-calendar.azurewebsites.net/index-bs3.html
I'm trying to load this project as described [link removed]
As in the demo, there is a dynamic list on the side of the calendar that does update with the events as you scroll through. How ever unlike the demo, my events are not getting listed in the calendar view. They don't show up on the calendar! :(
I did add a couple extra json data options, but the required ones weren't changed. Here's an example of my json data:
{
"success": 1,
"result": [{
"id": "########",
"title": "Event NAme",
"start_time": "2014-08-23T18:30:00-0500",
"start": "1408836600",
"end_time": "",
"end": "0",
"class": "event-info",
"url": "http://..."
}]
}
I don't think it's a bug, but not sure why it's not working as expected.
Their code:
onAfterEventsLoad: function(events) {
if(!events) {
return;
}
var list = $('#eventlist');
list.html('');
$.each(events, function(key, val) {
$(document.createElement('li'))
.html('' + val.title + '')
.appendTo(list);
});
},
My code:
'onAfterEventsLoad': function(events) {
if(!events) {
return;
}
var list = $('#eventlist');
list.html('');
$.each(events, function(key, val) {
var d = new Date(val.start_time),
date = weekday[d.getDay()] + ", " + monthNames[d.getMonth()] + " " + d.getDate() + ", " + d.getYear();
$(document.createElement('li'))
.html('<a title="' + date + '" href="' + val.url + '">' + val.title + '</a><br/><small>' + jQuery.timeago(d) + '</small>')
.appendTo(list);
});
},
The url you are trying to load events from is simply returning {"success":1} and not any events for the onAfterEventsLoad handler to iterate through.
This is the cause of your problem, the calendar code is all working fine as far as I can see.

JSON Loop through nested array

This is my JS ("data" is from the json call):
if (data.projectReports.length) {
for (var i in data.projectReports){
var report = data.projectReports[i];
$('#reports').append(
'<div class="report-description">' +
'<h2>' + report.header + '</h2>' +
'<p>' + report.text + '</p>' +
'</div>' +
'<ul class=\"report-moreinfo\">' +
// I want to loop through "persons" here.
'</ul>'
);
}
} else
. . .
This is my JSON:
{
"projectReports":[
{
"header":"Headline",
"text":"Description of item",
"estimate":10,
"actual":7,
"persons":{
"Robert":5,
"Erik":10,
"Juan":3
}
}
]
}
I am new to JSON and after searching for an answer and actually finding a few different answers, new problems arose so I thought I would post the question in it's entirety here.
Where the comment is in my JavaScript code, I want to loop through report.persons.
In all of the solutions I found they could point directly to "header" or "text" like I have done before, but in this case I just have a key and value. How would I go about doing something like this?
<li><p> persons.key </p><p> persons.value </p></li>
I understand that I will have to do another for loop, but my knowledge isn't good enough to be able to figure out on my own how to construct it.
This is pretty basic stuff
var personsMarkup = "";
for (var i in persons){
if (persons.hasOwnProperty(i)){
console.log(i); // the key
console.log(persons[i]); // the value
// cancat this all together
personsMarkup =+ "<li><p>"+i+"</p><p>"+persons[i]+"</p></li>";
}
}
and then:
$('#reports').append(
/* ... */
'<ul class=\"report-moreinfo\">' +
personsMarkup +
'</ul>';
/* ... */
);
For your code I'd use a function that loops through reports.persons and returns what you need:
var showPersons = function(persons){
var appendedData = '';
for (var person in persons) {
if (!persons.hasOwnProperty(person)) continue;
appendedData += '<li><p>' + person + '</p><p>' + persons[person] +'</p></li>'
}
return appendedData;
};
And now you can use this to append all that stuff inside the <ul> tags:
listPersons(report.persons);
If you wanted the code read closer to what you wanted (and to be able to use person.name and person.value), you'd need to have the JSON in this format:
{
"projectReports": [
{
"header": "Headline",
"text": "Description of item",
"estimate": 10,
"actual": 7,
"persons": [
{
"name": "Robert",
"value": 5
},
{
"name": "Erik",
"value": 10
},
{
"name": "Juan",
"value": 3
}
]
}
]
}
Use for (.. in ..)
$('#reports').append(
'<div class="report-description">' +
'<h2>' + report.header + '</h2>' +
'<p>' + report.text + '</p>' +
'</div>' +
'<ul class=\"report-moreinfo\">');
for (var personKey in report.persons){
$('#reports').append('<li><p>' + personKey + '</p><p>' + report.persons[personKey] + '</p></li>');
}
$('#reports').append(
'</ul>'
);

Categories

Resources