Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHerbert Grönemeyer
2,751 Pointslive search function working... Buggy?
Hi I tried to get a live search function working which is however acting wierd.. I removed all buttons and forms, leaving only the searchbar and used .keypress() to fire it:
$('#search').keypress(function (evt) {
// the AJAX part
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
var animal = $(this).val();;
var flickrOptions = {
tags: animal,
format: "json"
};
function displayPhotos(data) {
var photoHTML = '<ul>';
$.each(data.items,function(i,photo) {
photoHTML += '<li class="grid-25 tablet-grid-50">';
photoHTML += '<a href="' + photo.link + '" class="image">';
photoHTML += '<img src="' + photo.media.m + '"></a></li>';
}); // end each
photoHTML += '</ul>';
$('#photos').html(photoHTML);
}
$.getJSON(flickerAPI, flickrOptions, displayPhotos);
});
however, when I enter "cat" for example I get results for what I think is "catch" instead. I know we were told that you have no control on the order that the AJAX requests are coming back. But there must be a way right? I've seen this live search functionality on other sites...
Thanks!
2 Answers
Vitaliy Bogdanov
7,612 PointsFunction is ok. But there is one weak spot. The fact that the event "keypress" triggered earlier than changing the value of the input field. Therefore, the first time function send empty request, then the letter "c", and then "ca". It is easy to check to add console.log ($ (this) .val ()); in function start.
My solution is to change the event handler in the "keyup"
Or make use of the delay through setTimeout() and wait for the end of the input.
Daniel Zlatanov
3,695 PointsI have tried with .keyup() as suggested by Vitaliy and it works great!