This is a snippet of my code on my site which displays json data onto the html page however, theres a lot of data on the json file. how would I limit the number of movies(data) being shown to 5.
function actors(actors) {
return `
<h5>Actors</h5>
<ul class="actors-list">
${actors.map(actor => `<li>${actor}</li>`).join("")}
</ul>
`;
}
function movieTemplate(movie) {
return `
<div class="animal" >
<img class="movie-photo" src="${movie.info.image}">
<h2 class="movie-name">${movie.title} <span class="species">(${movie.info.rating})</span></h2>
<p><strong>Year:</strong> ${movie.year}</p>
${movie.info.actors ? actors(movie.info.actors) : ""}
</div>
`;
}
document.getElementById("app").innerHTML = `
<h1 class="app-title">movies (${movieData.length} results)</h1>
${movieData.map(movieTemplate).join("")}
<p class="footer">These ${movieData.length} movies were added recently. Check back soon for updates.</p>
Image
This image shows the data being shown however thousands of movies are being shown I only want 5.
To limit the data you can use the slice function arr.slice([begin[, end]])
<ul class="actors-list">
${actors.slice(0,5).map(actor => `<li>${actor}</li>`).join("")}
</ul>
Related
I have had trouble with a movie watch list project where i have two main pages (movie search page and watch list page) and one JS file they both share. I would like to be able to save a movie result after having searched for a movie on the first HTML page, and have it save to local storage and appear on the second HTML page.
I was able to create a watch list that lives on the same page as the movie search page and save selections temporarily, but when I refresh they disappeared. When I have tried saving to a separate page, I am unable to first fetch the ID where I want to insert the HTML data. I kind of understand this is because I am only able to load one page at at time, yet I have been unable to figure out what to do about it. I have also tried to use preventDefault to stop my second HTML page from refreshing in order to see if my data is saving, but i have been unsuccessful in this as well.
Here is my java script document which both pages share
function run(){
let ID
let movArr
document.querySelector("#search").addEventListener('click',async function(){
const movSearch = document.querySelector("#movieSearch").value
const res = await fetch(`https://www.omdbapi.com/?s=${movSearch}&type=Movie&apikey=3c746e2`)
const data = await res.json()
movArr = data.Search
html=""
for(let movie of movArr)
{
const rez = await fetch(`https://www.omdbapi.com/?i=${movie.imdbID}&type=Movie&apikey=3c746e2`)
const datatwo = await rez.json()
ID = datatwo.imdbID
html +=
` <div class="movieInput" style="display:flex;align-items:center">
<div>
<img src="${movie.Poster}" style="width:99px;margin:42px 0 0 44px">
</div>
<div></div>
<div style="margin:3px 0 0 21px">
<text style="font-weight:bold; font-size:18px">${movie.Title}</text>
<p>${datatwo.imdbRating}</p>
<div style="display:flex; gap:36px; font-size:12px">
<p>${datatwo.Runtime}</p> <p>${datatwo.Genre}</p> <p><i class="fa-solid fa-circle-plus" data-add="${datatwo.imdbID}"></i></p>
</div>
<div style="margin:-20px 0 0 0">
<p>${datatwo.Plot}</p>
</div>
</div>
</div>
<hr />`}
document.querySelector("#movies").innerHTML = html
}) }
function watchlist(){
localStorage.setItem( 'film' , JSON.stringify(html) )
document.querySelector('#moviesToo').innerHTML = JSON.parse(localStorage.getItem('film'))
}
function watch(){
let html
document.addEventListener('click', async function(e){
if(e.target.dataset.add){
console.log('clicked!')
const movie = e.target.dataset.add
const dez = await fetch(`https://www.omdbapi.com/?i=${movie}&type=Movie&apikey=3c746e2`)
const datathree = await dez.json()
ID = datathree.imdbID
html =
`
<div class="movieInput" style="display:flex;align-items:center">
<div>
<img src="${datathree.Poster}" style="width:99px;margin:42px 0 0 44px">
</div>
<div></div>
<div style="margin:3px 0 0 21px">
<text style="font-weight:bold; font-size:18px">${datathree.Title}</text>
<p>${datathree.imdbRating}</p>
<div style="display:flex; gap:36px; font-size:12px">
<p>${datathree.Runtime}</p> <p>${datathree.Genre}</p> <p><i class="fa-solid fa-circle-minus" data-add="${datathree.imdbID}"></i></p>
</div>
<div style="margin:-20px 0 0 0">
<p>${datathree.Plot}</p>
</div>
</div>
</div>
<hr />`}
return watchlist()
})
}
run()
watch()
Ok, this seems to be a easy question but I'm not able to get it.
I have index.php and find.php in my project.
In index.php, I'm showing results of list-group items as follows
<div id="showDetails">
</div>
<div id="showList">
//All my list-group items are listed here
</div>
My Ajax returning the list-group as follows
function funcReadRecord() {
var readrecord1 = "readrecord1";
var sometext = $('#SNOW_INC').val();
$.ajax({
url : "find.php",
type : 'post' ,
data : { readrecord1 : readrecord1,
sometext : sometext } ,
success : function(data, status){
$('#showList').html(data);
}
});
}
Now, I'm returning the values as a HTML link so it looks like this
<div id="showList">
data 1
data 2
data 3
</div>
What I want is when I click data 1 link, I want to show showDetails div with data 1 populated. Then when I click data 2 link, it changes to data 2 in showDetails.
How do I do that?
Probably the information I've provided is not enough but feel free to ask and I'll provide more.
The simplest solution would be to add a click handler to each item that calls a function, passing in the id of the item you want to display.
Within that function, fetch the data for the given item and show it.
function showData(which) {
console.log(`fetch data ${which} here and show it in the data div.`);
document.getElementById('showData').innerHTML = `show data ${which}`
return false; // prevents navigation on the clicked link
}
<div id="showList">
<a onclick="showData(1)" href="#">data 1</a>
<a onclick="showData(2)" href="#">data 2</a>
<a onclick="showData(3)" href="#">data 3</a>
</div>
<div id="showData"></div>
I'm creating a project with the use of Firebase and I'm having some issues with getting the data inside of my database to display in the DOM due to error "setupFoodGroup is not defined"...This is likely due to a rookie coding error, but I can't seem to work out where I've gone wrong.
Current code as per below:
// Get data from database
db.collection('foodgroups').get().then(snapshot => {
setupFoodGroup(snapshot.docs);
});
// Setting Up Food Lists
const foodList = document.querySelector('.foodGroups');
const setupFoodGroup = (data) => {
let html = '';
data.forEach(doc => {
const group = doc.data();
const li = `
<li>
<div class="card bg-light mb-3" style="max-width: 20rem;">
<div class="card-body">
<h4 class="card-title">${group.title}</h4>
<p class="card-text">${group.content}</p>
</>
</div>
</li>
`;
html += li
})
foodGroups.innerHTML = html;
};
I'm then wanting to get them displaying inside the following HTML on a display page
<div class="card-body">
<ul class="foodGroups">
</ul>
</div>
Any points would be very much appreciated.
Cheers!
I have a function which grabs comments from the server, I would like to display total number of comments available in a server.
Here is the function in .ts file:
this.activeRouter.params.subscribe(params => {
// tslint:disable-next-line:prefer-const
let id = params['id'];
this.userService.getComments(id)
.pipe(
map(data => data.sort((a, b) => new Date(b.localTime).getTime() - new Date(a.localTime).getTime()))
)
.subscribe(data => this.comments = data);
});
Here is the get function in service
getComments (id: number) {
return this.http.get<Comment[]>(this.commentsUrl);
}
Here is the html for displaying comments
<div class="comments-description" *ngFor="let comment of comments">
<span class="comments_count">(353)</span>
<div class="comments-photo">
<img src="https://randomuser.me/api/portraits/men/84.jpg" alt="">
</div>
<div class="comments_wrapper">
<div class="comments_details">
<h1>{{comment.author}}</h1>
<span class="days">1d</span>
</div>
<div class="comments_text">
<p>{{comment.description}} </p>
</div>
</div>
</div>
why not simply use the length
<span class="comments_count">{{comments.length}}</span>
If you get all the comments in the response then you can use comments.length
<span class="comments_count">{{comments.length}}</span>
But the best practice is to get it from the API side. Add one more field in your API response for comment count.
Solution:
While getting comments data from server , You have to return total number of comments along with the new data.
Once you call service you can add data in one array.
and set total count in one variable.
Note:
You have to read count from sever and return result in same API or service
Update your API and get comments count using API and show your comment count.
Such counter must be on the server side.
For example, post has 10000 comments.
1 request will not fetch them all, only a portion (page).
And it's not good to get them all only to find out a count.
So the response should contain a 'count' field.
The view in my html is not getting filtered on selecting any li element.
But when I console the filter functions the output generated is correct.Also how to clear the filter so it is reusable again.I'm getting a blank page on clicking open or close select elements.Can anyone help me with this.
I have used two filters in a controller inside the functions like this-
indexController Functions-
this.UserTickets = ()=> {
//code to get the tickets
}
this.openTickets = () => {
index.filteredTickets = $filter('filter')(index.tickets, { status: "open" } );
console.log(index.filteredTickets);
};
//filter closed tickets
this.closeTickets = () => {
index.filteredTickets = $filter('filter')(index.tickets, { status: "close" } );
console.log(index.filteredTickets);
};
this.clearFilter = () => {
//clear the filter
};
HTML-
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a ng-click="indexCtrl.clearfilter()">None</a></li>
<li><a ng-click="indexCtrl.openTickets()">Open</a></li>
<li><a ng-click="indexCtrl.closeTickets()">Close</a></li>
</ul>
<div ng-repeat="ticket in indexCtrl.tickets | filter:tickets |filter:indexCtrl.filteredTickets">
<div class="ticket-no">
<h4>Ticket No:<span>{{ticket}}</span></h4>
</div>
<div class="ticket-title">
<a ng-href="/ticketView/{{ticket.ticketid}}"><h3>{{ticket.title}}</h3></a>
</div>
<div class="ticket-info">
<p class="pull-left">{{ticket.username}} On {{ticket.created | date:"MMM d, y h:mm a"}}</p>
<p class="pull-right">Status:<span>{{ticket.status}}</span></p>
</div>
<hr class="hr">
</div>
You are mixing both angular filter options. I would recommend the javascript filters, index.filteredTickets=$filter('filter')(index.tickets,{status:"open"}); rather than the html template syntax, ng-repeat="ticket in indexCtrl.tickets | filter:tickets...". The key difference between these methods is how often they are run. The html template syntax filters are run on every digest cycle, the javascript filters are only run when the method is called, in your case, on each button click. For small apps or when the lists are small, this difference won't be noticeable, but if your app grows in size, the constant filtering on each digest cycle can cause page lag.
The filters in the controller are my preferred way of handling this, so I will show you how to clean up your code for these to work. You are almost there, just a few small changes are needed.
In your html, you can remove the inline filters in the ng-repeat, these aren't needed, and change the array to be your filter list, index.filteredTickets.
.html
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a ng-click="indexCtrl.clearfilter()">None</a></li>
<li><a ng-click="indexCtrl.openTickets()">Open</a></li>
<li><a ng-click="indexCtrl.closeTickets()">Close</a></li>
</ul>
<div ng-repeat="ticket in indexCtrl.filteredTickets">
<div class="ticket-no">
<h4>Ticket No:<span>{{ticket}}</span></h4>
</div>
<div class="ticket-title">
<a ng-href="/ticketView/{{ticket.ticketid}}"><h3>{{ticket.title}}</h3></a>
</div>
<div class="ticket-info">
<p class="pull-left">{{ticket.username}} On {{ticket.created | date:"MMM d, y h:mm a"}}</p>
<p class="pull-right">Status:<span>{{ticket.status}}</span></p>
</div>
<hr class="hr">
</div>
For the javascript, you need to make sure the filteredTickets are accessible in the html. I'm not sure if index == this, if not, you may need to attach the filtered tickets to the scope. The one other change needed is to set the filteredTickets to your original list if the none button is pressed. You will also want to call clearFilter after you load the list, otherwise index.filteredList will be undefined/null.
.js
this.UserTickets = () => {
//code to get the tickets
....
//after getting list, call clear filter
this.clearFilter();
}
this.openTickets = () => {
index.filteredTickets = $filter('filter')(index.tickets, { status: "open" } );
console.log(index.filteredTickets);
};
//filter closed tickets
this.closeTickets = () => {
index.filteredTickets = $filter('filter')(index.tickets, { status: "close" } );
console.log(index.filteredTickets);
};
this.clearFilter = () => {
//clear the filter
index.filteredTickets = index.tickets;
};