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 trial
piero borrelli
Full Stack JavaScript Techdegree Student 6,066 PointsSlice() doesn't work
Hello everybody, I'm currently going under the fullstack js techdegree. I'm currently on project two and I am having an issue with the slice() function. I use this function to only select the elements that I want to show from the html code.
Everything works fine except in one case. In this project we have to implement a search box, my code is made such as that when the search box is empty only the first then students are displayed.
The problem is that the slice() function in that case seems to stop working!. It works well in other cases but when I call it after checking for the $filter lenght it simply stops working.
Here is the link to the code, Thank you so much if You can help with this https://codepen.io/pieroBorrelli/pen/vdWYGQ
1 Answer
Joel Bardsley
31,258 PointsHi Piero,
With your current code, searchStudent() continues to run after you call goToPage(). If you check the Inspector in your browser developer tools, you'll see for yourself that slice does still work properly, but the other elements do not retain their 'display: none' styling because the rest of the searchStudent function is still running, and is applying fadeOut and show methods to each of the $students.
To get around this, you could update your if statement in searchStudent and have the fadeOut/show run only when $filter.length doesn't equal 0:
function searchStudent() {
$(".page-header").append($('<div class = "student-search"><input placeholder="Search for students..."> <button>Search</button> </div>'));
$('button').on('click', function() {
const $filter = $('input').val();
if($filter.length === 0) {
goToPage(0);
// fadeOut() and show() below no longer run
} else {
$students.each(function() {
if ($(this).text().search(new RegExp($filter, "i")) < 0) {
$(this).fadeOut();
} else {
$(this).show();
}
});
}
});
}
Hope that makes sense.