Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
48 changes: 48 additions & 0 deletions functionNames.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// adds a listener to the search submit button
function formListener () {

function articleTemplate(article, articleDomain) {
return

// takes request body and turns it into html to be appended into 'main'
function createArticles(body) {

// api request to news api. Returns json and calls createArticles function
function getArticles(page=1, excludedDomainsStr='', filterDomains="") {

// add a listener to article creating 'click' event that takes user to URL
function clickArticle(articleNode, url) {

// adds listeners that change the colour of the article the mouse is over
function mouseOverArticle(articleNode) {



// clears existing articles from page in preparation for a new search or new page
function clearArticles() {

// clears publishers
function clearPublishers() {

// clears pagination
function clearPagination() {

function excludeDomain(articleDomain) {

// creates red buttons for excluded domains / publishers at top of page.
function createExcluded() {



// adds 5 page links to bottom of page
function addPagination(totalResults) {

function publisherCount(articles) {
clearPublishers();

global

const publisherObject = [];
const excludedDomainsArray = [];
let search = "uk";
let itemId = 1;
Binary file added images/.DS_Store
Binary file not shown.
Binary file added images/blank.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/header-ventoux.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/news-etc.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
64 changes: 64 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Phil's Newsreader.</title>
<link href="https://fonts.googleapis.com/css?family=Lato|Open+Sans" rel="stylesheet"> <link rel="stylesheet" href="style.css">
</head>

<body>
<div class="app">
<div class="hero__photo"></div>
<div class="top">
<header>
<div class="header__logo"><img src="images/news-etc.png"></div>
<div class="header__description"></div>
<div class="header__search">
<form>
<input type="search" id="form-search" name="form-search" />
<button type="submit" id="form_button">Search</button>
</form>
</div>

</header>
</div>


<main>
<div class="sideOrTopBar">
<div class="excludedDomainsDiv">
<span class="excludedDomains__message">Excluded publishers<br> Click to re-apply.</span>
<ul class="excludedDomains">

</ul>
</div>
<div class="publishers">
<div class="publisher__list">

</div>
</div>
</div>

<div class="articles">



</div>


</main>
<ul class="pagination__ul">
</ul>
<footer>

</footer>
</div>

</body>
<script src="index.js"></script>

</html>
230 changes: 230 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
let itemId = 1;
let hundredArticles = [];


// adds a listener to the search submit button
const formListener = () => {
const formElement = document.querySelector("form");
const formInput = document.querySelector("#form-search");
formElement.addEventListener('submit', event => {
event.preventDefault();
search = formInput.value;
page=1;
getArticles(1,excludedDomainsArray);
});
}

// api request to news api. Returns json and calls createArticles function
const getArticles = (page=1, excludedDomainsStr='', filterDomains="") => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice

console.log('Function : Fetching Articles (getArticles)');
var url = 'https://newsapi.org/v2/everything?' +
'q=' + search +
'&page=' + page +
'&apiKey=280f7af9f5c448c4a3598861960c947a' +
'&excludeDomains=' + excludedDomainsStr + '&domains=' + filterDomains + '&pageSize=100&sortBy=publishedAt&language=en';
var req = new Request(url);
fetch(req)
.then(function (response) {
return response.json();
})
.then(function (body) {
hundredArticles = body.articles;
createArticles(0);
createExcluded();
publisherCount(body.articles);
addPagination(body.totalResults);

})
}


// takes request body and turns it into html to be appended into '.articles'
const createArticles = (startArticle) => {
console.log('Function : Creating Articles (createArticles)');
clearDiv('.articles');
// console.log(hundredArticles);

twentyArticles = hundredArticles.slice(startArticle,startArticle+20);
itemId = 0;
twentyArticles.forEach(article => {
itemId ++
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can get the itemId using forEach index for example twentyArticles.forEach((article, index)){

const articleNode = document.createElement('div');
articleNode.className = "article";
let articleDomain = article.url.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
articleNode.innerHTML = articleTemplate(article,articleDomain, itemId);
const parentNode = document.querySelector('.articles');
parentNode.appendChild(articleNode);
const excludeDomainSpan = document.createElement('span');
excludeDomainSpan.textContent = "Exclude Publisher";
excludeDomainSpan.className = "excludeButton";
const excludeDomainSpanParent = document.querySelector(`#item${itemId}`);
excludeDomainSpanParent.appendChild(excludeDomainSpan);
excludeDomainSpan.addEventListener("click", event => {
excludeDomain(articleDomain);
console.log(articleDomain);
})
mouseOverArticle(articleNode)
clickArticle(articleNode, article.url);
document.body.scrollTop = document.documentElement.scrollTop = 0;
});
};

const articleTemplate = (article, articleDomain) => {
if (!article.urlToImage) {
article.urlToImage="images/blank.gif";
};
if (!article.description) {
article.description=" ";
};

dateSlicedAndSplit = (article.publishedAt.slice(0,10).split('-'));

return `
<div class="article__title"><a href="${article.url}">${article.title}</a></div>
<div class="article__content">
<div class="article__description">${article.description}</div>
<div class="article__image"><img src="${article.urlToImage}"></div>
</div>
<div class="article__meta">
<div class="article__publication">${article.source.name}<p id="item${itemId}"></p></div>
<div class="article__date">${dateSlicedAndSplit[2]} - ${dateSlicedAndSplit[1]} - ${dateSlicedAndSplit[0]}</div>
</div>`
}

// add a listener to article creating 'click' event that takes user to URL
const clickArticle = (articleNode, url) => {
articleNode.addEventListener("click", event => {
window.location = url;
})
}


function excludeDomain(articleDomain) {
event.stopPropagation();
if (!excludedDomainsArray.includes(articleDomain)) {
excludedDomainsArray.push(articleDomain);
}
getArticles(1,excludedDomainsArray.toString());
}

// creates red buttons for excluded domains / publishers at top of page.
function createExcluded() {
document.querySelector('.excludedDomains').innerHTML = "";
if (excludedDomainsArray.length>0) {
document.querySelector('.excludedDomains__message').style.display = 'flex';
excludedDomainsArray.forEach(domain => {
const parentNode = document.querySelector('.excludedDomains');
const childNode = document.createElement('li');
childNode.className = "excludedDomains__li";
childNode.innerHTML = domain;
parentNode.appendChild(childNode);
childNode.addEventListener("click", event => {
excludedDomainsArray.splice(excludedDomainsArray.indexOf(domain),1);
getArticles();
})
})
document.querySelector('.excludedDomainsDiv').style.display = 'flex';
} else {
document.querySelector('.excludedDomainsDiv').style.display = 'none';
}
if (excludedDomainsArray.length > 4) {
document.querySelector('.excludedDomainsDiv').style.flexDirection = 'column';
}
}









// adds 5 page links to bottom of page
function addPagination(totalResults) {
clearDiv('.pagination__ul');
let numberOfPages = Math.floor(totalResults/20)+1;
if (numberOfPages > 5) {numberOfPages = 5};
for (i=1;i<=numberOfPages;i++) {
const pageLinkNode = document.createElement('li');
const parentNode = document.querySelector('.pagination__ul');
pageLinkNode.innerHTML = i;
pageLinkNode.className = "pagination__page";
parentNode.appendChild(pageLinkNode);
pageLinkNode.addEventListener("click", event => {createArticles((pageLinkNode.innerHTML-1)*20)});
}
}

// counts the articles on the search query by publisher and sorts them. Publisher can be clicked to show search by term + publishers filter.
// can definitely be re-written. Seems like a pretty messy way of sortinging that I've used.

const publisherCount = (articles) => {
clearDiv('.publisher__list');
let publishersNames = [];
const publishersObjects = {};
const publishersCount = [];

articles.forEach(article => {
if (!publishersNames.includes(article.source.name)) {
let articleDomain = article.url.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
publishersNames.push(article.source.name)
publishersObjects[article.source.name]= {name:article.source.name,domain:articleDomain,count:1}
} else {
publishersObjects[article.source.name].count++;
}
})

publishersNames.forEach(publisher => {
publishersCount.push([publishersObjects[publisher].name,publishersObjects[publisher].count]);
})

publishersCount.sort(function(b, a) {
return a[1] - b[1];
});

publishersNames =[];

publishersCount.forEach(publisher => {
publishersNames.push(publisher[0]);
})

let topTenPublishers = publishersNames.slice(0,10);

topTenPublishers.forEach(publisher => {
const parentNode = document.querySelector('.publisher__list');
const childNode = document.createElement('div');
childNode.textContent = `${publisher} (${publishersObjects[publisher].count})`;
parentNode.appendChild(childNode);
childNode.addEventListener("click", event => {getArticles(1,"",publishersObjects[publisher].domain)})
})
}


// adds listeners that change the colour of the article the mouse is over - move to css
const mouseOverArticle = (articleNode) => {
articleNode.addEventListener("mouseover", event => {
articleNode.style.backgroundColor = "#ffc754";
})
articleNode.addEventListener("mouseout", event => {
articleNode.style.backgroundColor = "white";
})
}


const clearDiv = (divClass) => {
const mainNode = document.querySelector(divClass);
mainNode.innerHTML = "";
};

const publisherObject = [];
const excludedDomainsArray = [];
let search = "uk";


getArticles();
formListener();





Loading