forked from bradtraversy/finddit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
80 lines (72 loc) · 2.44 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import reddit from './redditapi';
const searchForm = document.getElementById('search-form');
const searchBtn = document.getElementById('search-btn');
const searchInput = document.getElementById('search-input');
searchForm.addEventListener('submit', e => {
// Get sort
const sortBy = document.querySelector('input[name="sortby"]:checked').value;
// Get limit
const searchLimit = document.getElementById('limit').value;
// Get search
const searchTerm = searchInput.value;
// Check for input
if (searchTerm == '') {
// Show message
showMessage('Please add a search term', 'alert-danger');
}
// Clear field
searchInput.value = '';
// Search Reddit
reddit.search(searchTerm, searchLimit, sortBy).then(results => {
let output = '<div class="card-columns">';
console.log(results);
results.forEach(post => {
// Check for image
let image = post.preview
? post.preview.images[0].source.url
: 'https://cdn.comparitech.com/wp-content/uploads/2017/08/reddit-1.jpg';
output += `
<div class="card mb-2">
<img class="card-img-top" src="${image}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">${post.title}</h5>
<p class="card-text">${truncateString(post.selftext, 100)}</p>
<a href="${post.url}" target="_blank
" class="btn btn-primary">Read More</a>
<hr>
<span class="badge badge-secondary">Subreddit: ${post.subreddit}</span>
<span class="badge badge-dark">Score: ${post.score}</span>
</div>
</div>
`;
});
output += '</div>';
document.getElementById('results').innerHTML = output;
});
e.preventDefault();
});
// Show Message Function
function showMessage(message, className) {
// Create div
const div = document.createElement('div');
// Add classes
div.className = `alert ${className}`;
// Add text
div.appendChild(document.createTextNode(message));
// Get parent
const searchContainer = document.getElementById('search-container');
// Get form
const search = document.getElementById('search');
// Insert alert
searchContainer.insertBefore(div, search);
// Timeout after 3 sec
setTimeout(function() {
document.querySelector('.alert').remove();
}, 3000);
}
// Truncate String Function
function truncateString(myString, limit) {
const shortened = myString.indexOf(' ', limit);
if (shortened == -1) return myString;
return myString.substring(0, shortened);
}