Updated Search functionality

This commit is contained in:
Nik Topler 2020-09-20 00:44:09 +02:00
parent 2dd3a0f0b7
commit 7ed059318f
12 changed files with 400 additions and 288 deletions

View file

@ -14,7 +14,6 @@ body{
font-family: 'Noto Sans', sans-serif; font-family: 'Noto Sans', sans-serif;
} }
.select-div{ .select-div{
position: relative; position: relative;
padding: 10px; padding: 10px;

View file

@ -1,7 +1,7 @@
body{ body{
display: grid; display: grid;
grid-template-rows: 65px 1fr; grid-template-rows: 65px 1fr;
overflow: hidden; overflow: auto;
} }
/*? Navigation Bar */ /*? Navigation Bar */
@ -413,7 +413,7 @@ body{
width: 17.5rem; width: 17.5rem;
overflow: hidden; overflow: hidden;
} }
.side-bar-content{ .side-bar-content {
font-size: 0.875rem; font-size: 0.875rem;
height: 100%; height: 100%;
width: 17.5rem; width: 17.5rem;
@ -537,11 +537,12 @@ body{
} }
/** Main Section */ /** Main Section */
.main-content-section { .main-content-section {
width: 1180px; max-width: 1176px;
min-width: 500px; width: 1080px;
min-width: 250px;
height: 100%; height: 100%;
padding: 20px; padding: 20px;
margin-top: 65px; margin: auto;
} }
.main-content-container { .main-content-container {
height: 100%; height: 100%;
@ -1330,15 +1331,22 @@ body{
} }
/** Responsiveness */ /** Responsiveness */
/* @media screen and (max-width: 930px) { /* @media screen and (max-width: 1150px) {
.navigation-bar{ .article-container {
grid-template-columns: 120px 1fr 85px; grid-column: 1/8;
} }
.main-search-input,.extra-option-icon{ #main-side-content-container {
display: none; grid-column: 8/13;
} }
.search-icon-figure{ } */
grid-column: 3/4; @media screen and (max-width: 1681px) {
.main-content-section {
margin-left: 280px;
}
}
@media screen and (max-width: 1100px) {
.main-content-section {
margin-left: 0px;
} }
.side-bar-content { .side-bar-content {
background-color: var(--bg); background-color: var(--bg);
@ -1346,6 +1354,29 @@ body{
overflow: auto; overflow: auto;
z-index: 2; z-index: 2;
} }
.side-bar-content {
} */ left: -280px;
}
}
@media screen and (max-width: 964px) {
.navigation-bar { grid-template-columns: 120px 1fr 85px; }
.main-search-input,
.extra-option-icon {
display: none;
}
.search-icon-figure{
grid-column: 3/4;
}
}
/* Ipad */
@media screen and (max-width: 768px) {
#main-side-content-container {
display: none;
}
.article-container {
grid-column: 1/13;
}
.main-content-section {
width: 100%;
}
}

View file

@ -302,4 +302,4 @@ for (let i = 0; i < replacementList.length; i++) {
for (let j = 0; j < chars.length; j++) for (let j = 0; j < chars.length; j++)
diacriticsMap[chars[j]] = replacementList[i].base diacriticsMap[chars[j]] = replacementList[i].base
} }
function removeDiacritics(str) { return str.replace(/[^\u0000-\u007e]/g, function(c) { return diacriticsMap[c] || c }) } function removeDiacritics(str) { return str.replace(/[^\u0000-\u007e]/g, (c) => { return diacriticsMap[c] || c }) }

View file

@ -71,12 +71,13 @@ const searchBox = {
update : async (query) => { update : async (query) => {
let i = 0 let i = 0
let images = await searchBox.fetch(query) let images = await searchBox.fetch(query)
let searchAside = document.querySelector('article.search.aside')
if(images.hits.length === 0) { if(images.hits.length === 0) {
images = await searchBox.fetch('nature') images = await searchBox.fetch('nature')
i = Math.round(Math.random() * images.hits.length) i = Math.round(Math.random() * images.hits.length)
} searchAside.firstElementChild.lastElementChild.innerHTML = 'Search'
} else searchAside.firstElementChild.lastElementChild.innerHTML = 'Topic'
let searchAside = document.querySelector('article.search.aside')
searchAside.firstElementChild.firstElementChild.innerHTML = capitalizeString(mainSearchInput.value) searchAside.firstElementChild.firstElementChild.innerHTML = capitalizeString(mainSearchInput.value)
searchAside.firstElementChild.querySelector('figure img').src = images.hits[i].webformatURL searchAside.firstElementChild.querySelector('figure img').src = images.hits[i].webformatURL
searchAside.firstElementChild.querySelector('figure img').classList.remove('disable') searchAside.firstElementChild.querySelector('figure img').classList.remove('disable')
@ -93,6 +94,7 @@ let mouseSuggestHover = false
let moreSuggestWordsArray = [] let moreSuggestWordsArray = []
const suggest = { const suggest = {
fetch : async (input) => { fetch : async (input) => {
// const res = await fetch(`https://api.datamuse.com/words?ml=${input}`)
const res = await fetch(`https://api.datamuse.com/sug?s=${input}`) const res = await fetch(`https://api.datamuse.com/sug?s=${input}`)
return words = await res.json() return words = await res.json()
}, },
@ -102,11 +104,12 @@ const suggest = {
let input = mainSearchInput.value.split(' ') let input = mainSearchInput.value.split(' ')
let n = 0 let n = 0
while(suggestWordsArray.length < 16) { while(suggestWordsArray.length < 21) {
fetchArray = await suggest.fetch(input[n]) fetchArray = await suggest.fetch(input[n])
for(let i = 0; i < fetchArray.length; i++) for(let i = 0; i < fetchArray.length; i++)
if(suggestWordsArray.indexOf(fetchArray[i].word) === -1 && fetchArray[i].word !== mainSearchInput.value) suggestWordsArray.push(fetchArray[i].word) if(suggestWordsArray.indexOf(fetchArray[i].word) === -1 && fetchArray[i].word !== mainSearchInput.value) suggestWordsArray.push(fetchArray[i].word)
input[n] = removeCharactersInString(input[n], 0, -1) input[n] = removeCharactersInString(input[n], 0, -1)
if(input.length === 0) break if(input.length === 0) break
} }
@ -161,7 +164,7 @@ const suggest = {
selectSuggestedSearchOption : (element) => { selectSuggestedSearchOption : (element) => {
removeActiveSidebarCategory() removeActiveSidebarCategory()
hideSuggestWords() hideSuggestWords()
let elementInnerHTML = addCharacterBetweenSpaceInString(element.innerHTML, ' ', '+') let elementInnerHTML = removeDiacritics(element.innerHTML).trim()
let selectedCountryAcronym = getCountryAcronym(selectedCountry.innerHTML) let selectedCountryAcronym = getCountryAcronym(selectedCountry.innerHTML)
historyPushState(location.origin + location.pathname, `?q=${elementInnerHTML}&`, `cou=${selectedCountryAcronym}&`,`bg=${backgroundColor}`) historyPushState(location.origin + location.pathname, `?q=${elementInnerHTML}&`, `cou=${selectedCountryAcronym}&`,`bg=${backgroundColor}`)
mainSearch() mainSearch()
@ -169,32 +172,31 @@ const suggest = {
} }
const responsiveVersion = { const responsiveVersion = {
mobileVersionNavigationBar() { // mobileVersionNavigationBar() {
mainSearchIcon.classList.add('disable') // mainSearchIcon.classList.add('disable')
mainSearchBackLeftIcon.classList.remove('disable') // mainSearchBackLeftIcon.classList.remove('disable')
navigationBarLeft.classList.add('disable') // navigationBarLeft.classList.add('disable')
navigationBarRight.classList.add('disable') // navigationBarRight.classList.add('disable')
navigationBarMiddle.style.gridColumn = '1/4' // navigationBarMiddle.style.gridColumn = '1/4'
mainSearchFigure.style.gridColumn = '1/2' // mainSearchFigure.style.gridColumn = '1/2'
mainSearchBackLeftTooltiptext.classList.remove('disable') // mainSearchBackLeftTooltiptext.classList.remove('disable')
mainSearchInput.style.display = 'grid' // mainSearchInput.style.display = 'grid'
extOptIcon.style.display = 'flex' // extOptIcon.style.display = 'flex'
mainSearchInput.focus() // mainSearchInput.focus()
sideBarContent.style.left = '-100%' // sideBarContent.style.left = '-100%'
sideMenuCounter = 1 // sideMenuCounter = 1
}, // },
desktopVersionNavigationBar() { // desktopVersionNavigationBar() {
mainSearchIcon.classList.remove('disable') // mainSearchIcon.classList.remove('disable')
mainSearchBackLeftIcon.classList.add('disable') // mainSearchBackLeftIcon.classList.add('disable')
navigationBarLeft.classList.remove('disable') // navigationBarLeft.classList.remove('disable')
navigationBarRight.classList.remove('disable') // navigationBarRight.classList.remove('disable')
navigationBarMiddle.style.gridColumn = '2/3' // navigationBarMiddle.style.gridColumn = '2/3'
mainSearchFigure.style.gridColumn = '3/4' // mainSearchFigure.style.gridColumn = '3/4'
mainSearchBackLeftTooltiptext.classList.add('disable') // mainSearchBackLeftTooltiptext.classList.add('disable')
mainSearchInput.style.display = 'none' // mainSearchInput.style.display = 'none'
extOptIcon.style.display = 'none' // extOptIcon.style.display = 'none'
} // }
} }
const regularExpressions = { const regularExpressions = {
@ -225,7 +227,43 @@ const php = {
} }
} }
const error = {
headlines : () => {
},
search : () => {
if(!window.location.search.match(regularExpressions.url.country)
|| !window.location.search.match(regularExpressions.url.backgroundColor)
|| !window.location.search.match(regularExpressions.url.search)) openLinks(filePath.headlines)
}
}
// const error = {
// headlines : () => {
// },
// search : () => {
// // let countryAcronym = window.location.search.match(regularExpressions.url.country)[0].slice(5, 7)
// if(!window.location.search.match(regularExpressions.url.country)
// || !getAcronymCountry(countryAcronym)
// || !window.location.search.match(regularExpressions.url.query)
// || !window.location.search.match(regularExpressions.url.backgroundColor))
// openLinks(filePath.headlines)
// else {
// let urlCountryAcronym = countryAcronym
// let urlCountry = getAcronymCountry(urlCountryAcronym)
// updateCountrySelect(urlCountry)
// }
// }
// }
window.onload = async () => { window.onload = async () => {
// Close all open windows
hideExtraSearchOptions()
hideSuggestWords()
document.querySelectorAll('input').forEach(input => { input.autocomplete = 'off' })
await user.location() await user.location()
removeActiveSidebarCategory() removeActiveSidebarCategory()
if (window.location.pathname.includes('headlines')) headlines() if (window.location.pathname.includes('headlines')) headlines()
@ -245,27 +283,14 @@ window.onload = async () => {
else if (window.location.pathname.includes('search')) mainSearch() else if (window.location.pathname.includes('search')) mainSearch()
// changeBackgroundColor() // changeBackgroundColor()
let selectedCountryAcronym = getCountryAcronym(selectedCountry.innerHTML)
// if(!window.location.search.match(regularExpressions.url.country)) // let query = location.search.match(regularExpressions.url.query)[0]
// query = removeCharactersInString(query, 3, query.length - 1)
//historyPushState(window.location.origin + window.location.pathname, '', `?cou=${selectedCountryAcronym}&`,`bg=${backgroundColor}`)
// else {
// urlCountryAcronym = window.location.search.match(regularExpressions.url.country)[0].slice(5, 7)
// if(getAcronymCountry(urlCountryAcronym) === undefined) return openLinks(filePath.headlines)
// urlCountry = getAcronymCountry(urlCountryAcronym)
// updateCountrySelect(urlCountry)
// }
if(!window.location.search.match(regularExpressions.url.query)) return
let query = location.search.match(regularExpressions.url.query)[0]
query = removeCharactersInString(query, 3, query.length - 1)
/* Search news */ /* Search news */
} }
window.onclick = (e) => { window.onclick = (e) => {
if(logInOptions.classList.contains('active')) clickInOutCheck(logInOptions, e.target) if(logInOptions.classList.contains('active')) clickInOutCheck(logInOptions, e.target)
else if(!suggestMainInput.classList.contains('disable')) clickInOutCheck(suggestMainInput, e.target) else if(!suggestMainInput.classList.contains('disable')) clickInOutCheck(suggestMainInput, e.target)
else if(!extOptProfile.classList.contains('disable')) clickInOutCheck(extOptProfile, e.target) else if(!extOptProfile.classList.contains('disable')) clickInOutCheck(extOptProfile, e.target)
@ -279,18 +304,6 @@ function historyPushState(webiste, string, country, background) { history.pushSt
function changeBackgroundColor() { document.body.className = window.location.search.match(regularExpressions.url.backgroundColor)[0].slice(4,10) } function changeBackgroundColor() { document.body.className = window.location.search.match(regularExpressions.url.backgroundColor)[0].slice(4,10) }
// console.log(changeDiacritics())
// function changeDiacritics() {
// let string = 'leščać'
// string = string.split('')
// console.log(string)
// // const regexDiacritics = /č|ć|đ|š|ž/g
// for(let i = 0; i < string.length; i++)
// if(diacriticLetters.test(string[i]))
// string[i] = diacriticsReplacement[string[i]]
// return string
// }
function getLanguageAcronym(target) { function getLanguageAcronym(target) {
for(let i = 0; i < language.length; i++) for(let i = 0; i < language.length; i++)
if(language[i] === target) if(language[i] === target)
@ -312,7 +325,6 @@ function getAcronymLanguage(acronym) {
return language[i] return language[i]
} }
function changeTemperatureUnit(element) { function changeTemperatureUnit(element) {
const unit = element.innerHTML const unit = element.innerHTML
const temperatureElements = document.querySelectorAll('.temperature') const temperatureElements = document.querySelectorAll('.temperature')
@ -366,72 +378,77 @@ function fahrenheitToCelsius(number) { return (number - 32) * 5/9 }
function fahrenheitToKelvin(number) { return (number - 32) * 5/9 + 273 } function fahrenheitToKelvin(number) { return (number - 32) * 5/9 + 273 }
/* HEADLINES */ /* HEADLINES */
async function headlines() { async function headlines() {
// await weather.getWeather() // await weather.getWeather()
// weather.updateWeather() // weather.updateWeather()
sidebarCategorySelect(document.querySelector('.fa-newspaper').parentElement) sidebarCategorySelect(document.querySelector('.fa-newspaper').parentElement)
historyPushState(window.location.origin + window.location.pathname, '', `?cou=${getCountryAcronym(selectedCountry.innerHTML)}`,`&bg=${backgroundColor}`)
} }
/* SEARCH */ /* SEARCH */
function mainSearch(extra) { function mainSearch(extra, type) {
if(!window.location.pathname.includes('search')) return newSearch(extra) let url = ''
if(window.location.search.match(regularExpressions.url.query) === null) return openLinks(filePath.headlines) let newSearch = false
// error.search()
if(!type) type = 'main-url'
if(!window.location.pathname.includes('search')) newSearch = true
if(window.location.search.match(regularExpressions.url.query) === null && newSearch === false) return openLinks(filePath.headlines)
if(!extra && newSearch === true) {
url = removeDiacritics(mainSearchInput.value).trim()
return openLinks(filePath.search + `?q=${url}&cou=${getCountryAcronym(selectedCountry.innerHTML)}&bg=${backgroundColor}`)
} else if(extra && newSearch === true) {
url = createUrlExtraOptions()
return openLinks(filePath.search + url[1] + url[2] + url[3])
} else if(!extra && newSearch === false) {
addDisableSideElements() addDisableSideElements()
// console.log(extra === undefined) url = createUrlExtraOptions(type)
if(extra === undefined) { historyPushState(url[0], url[1], url[2], url[3])
let searchInputValue = window.location.search.match(regularExpressions.url.query)[0].slice(3, -1) let searchInputValue = window.location.search.match(regularExpressions.url.query)[0].slice(3, -1)
mainSearchInput.value = addCharacterBetweenSpaceInString(searchInputValue, '+', ' ') mainSearchInput.value = urlEdit(searchInputValue)
searchBox.update(mainSearchInput.value.trim()) } else if(extra && newSearch === false) {
} else { addDisableSideElements()
let extraOptionsUrl = createUrlExtraOptions() url = createUrlExtraOptions()
let selectedCountryAcronym = getCountryAcronym(selectedCountry.innerHTML) historyPushState(url[0], url[1], url[2], url[3])
historyPushState(websiteURL, extraOptionsUrl, selectedCountryAcronym, backgroundColor)
} }
let searchInputValue = window.location.search.match(regularExpressions.url.query)[0].slice(3, -1)
mainSearchInput.value = urlEdit(searchInputValue)
searchBox.update(mainSearchInput.value.trim())
hideExtraSearchOptions()
hideSuggestWords() hideSuggestWords()
suggest.suggest() suggest.suggest()
/* Search news articles */ /* Search news articles */
// console.log(url[4])
} }
function createUrlExtraOptions(option) {
function newSearch(extra) {
if(extra !== undefined) {
}
// if(mainSearchInput.value.length === 0) return
// if(!mainSearchIcon.classList.contains('disable') && window.innerWidth < 930) mobileVersionNavigationBar()
// else if(mainSearchIcon.classList.contains('disable') && window.innerWidth > 930) desktopVersionNavigationBar()
// let selectedCountryAcronym = getCountryAcronym(selectedCountry.innerHTML)
// if(extraSearchOptions.classList.contains('disable')) searchQuery = addCharacterBetweenSpaceInString(mainSearchInput.value,' ','+')
// else {
// let urlPath = createUrlPath('search', searchQuery)
// return console.log(urlPath)
// }
}
function createUrlExtraOptions() {
let url let url
let exactPhraseV = exactPhrase.value.trim() let exactPhraseV = removeDiacritics(exactPhrase.value).trim().replace(/\s\s+/g, ' ')
let hasWordsV = hasWords.value.trim() let hasWordsV = removeDiacritics(hasWords.value).trim().replace(/\s\s+/g, ' ')
let excludeWordsV = excludeWords.value.trim() let excludeWordsV = removeDiacritics(excludeWords.value).trim().replace(/\s\s+/g, ' ')
let time = `&t=${indexTimeLabel.innerHTML.trim().replace(' ','').toLowerCase()}`
if(exactPhraseV.length !== 0 && hasWordsV.length === 0 && excludeWordsV.length === 0) url = `"${exactPhraseV.trim()}"` resetExtraSearchOptions()
else if(hasWordsV.length !== 0 && exactPhraseV.length === 0 && excludeWordsV.length === 0) url = addCharacterBetweenSpaceInString(hasWordsV, ' ', '+')
else if(excludeWordsV.length !== 0 && exactPhraseV.length === 0 && hasWordsV.length === 0) url = addCharacterBetweenSpaceInString(excludeWordsV, ' ', '-') if(option === 'main-url') {
// else if (exactPhraseV.length !== 0 && hasWordsV.length !== 0 && excludeWordsV.length === 0) return `"${exactPhraseV}"+${devideStringIntoWords(hasWordsV,'HW')}` url = removeDiacritics(window.location.search.match(regularExpressions.url.query)[0].slice(3, -1))
// else if(hasWordsV.length !== 0 && excludeWordsV.length !== 0 && exactPhraseV.length === 0) return `${devideStringIntoWords(hasWordsV,'HW')} ${devideStringIntoWords(excludeWordsV,'EW')}` time = ''
// else if(exactPhraseV.length !== 0 && excludeWordsV.length !== 0 && hasWordsV.length === 0) return `"${exactPhraseV}" ${devideStringIntoWords(excludeWordsV,'EW')}` } else if(option === 'main-input') {
// else if(exactPhraseV.length !== 0 && excludeWordsV.length !== 0 && hasWordsV.length !== 0) return `"${exactPhraseV}" ${devideStringIntoWords(hasWordsV,'HW')} ${devideStringIntoWords(excludeWordsV,'EW')}` url = removeDiacritics(mainSearchInput.value).trim()
return url time = ''
// historyPushState(location.origin + location.pathname, `?q=${addCharacterBetweenSpaceInString(mainSearchInput.value, ' ', '+')}&`, `cou=${getCountryAcronym(selectedCountry.innerHTML)}&`,`bg=${backgroundColor}`) } else if(exactPhraseV.length !== 0 && hasWordsV.length === 0 && excludeWordsV.length === 0) url = `"${exactPhraseV}"`
else if(hasWordsV.length !== 0 && exactPhraseV.length === 0 && excludeWordsV.length === 0) url = hasWordsV
else if(excludeWordsV.length !== 0 && exactPhraseV.length === 0 && hasWordsV.length === 0) url = `-${excludeWordsV}`
else if (exactPhraseV.length !== 0 && hasWordsV.length !== 0 && excludeWordsV.length === 0) url = `"${exactPhraseV}" ${hasWordsV}`
else if(hasWordsV.length !== 0 && excludeWordsV.length !== 0 && exactPhraseV.length === 0) url = `${hasWordsV} ${devideStringIntoWords(excludeWordsV, 'EW')}`
else if(exactPhraseV.length !== 0 && excludeWordsV.length !== 0 && hasWordsV.length === 0) url = `"${exactPhraseV}" ${devideStringIntoWords(excludeWordsV, 'EW')}`
else if(exactPhraseV.length !== 0 && excludeWordsV.length !== 0 && hasWordsV.length !== 0) url = `"${exactPhraseV}" ${hasWordsV} ${devideStringIntoWords(excludeWordsV, 'EW')}`
return [`${location.origin}/News-website/search.php`,`?q=${url + time}`,`&cou=${getCountryAcronym(selectedCountry.innerHTML)}`,`&bg=${backgroundColor}`, url]
} }
function devideStringIntoWords(string, keyword){ function devideStringIntoWords(string, keyword){
if(keyword === 'HW') return `+${string.replace(/\s/g, ' +')}` if(keyword === 'HW') return `+${string.replace(/\s/g, ' +')}`
@ -473,7 +490,7 @@ function about() {
} }
mainSearchInput.onfocus = () => { mainSearchInput.onfocus = () => {
if(!extraSearchOptions.classList.contains('disable')) return manageExtraSearchOptions() if(!extraSearchOptions.classList.contains('disable')) return hideExtraSearchOptions()
else if(mainSearchInput.value.length !== 0) showSuggestWords() else if(mainSearchInput.value.length !== 0) showSuggestWords()
suggest.manageSuggestWords() suggest.manageSuggestWords()
} }
@ -488,18 +505,12 @@ mainSearchInput.onkeyup = (e) => {
let suggestDivs = suggestMainInput.querySelectorAll('div') let suggestDivs = suggestMainInput.querySelectorAll('div')
let suggestDivActiveKey = suggestMainInput.querySelectorAll('div.active.key') let suggestDivActiveKey = suggestMainInput.querySelectorAll('div.active.key')
if(e.keyCode === 13) { if(e.keyCode === 13) {
if(suggestDivActiveKey.length === 1) historyPushState(location.origin + location.pathname, `?q=${removeDiacritics(suggestDivActiveKey[0].firstElementChild.innerHTML).trim()}&`, `cou=${getCountryAcronym(selectedCountry.innerHTML)}&`,`bg=${backgroundColor}`)
if(suggestDivActiveKey.length === 1)//historyPushState else historyPushState(location.origin + location.pathname, `?q=${removeDiacritics(mainSearchInput.value).trim()}&`, `cou=${getCountryAcronym(selectedCountry.innerHTML)}&`,`bg=${backgroundColor}`)
console.log(location.origin + location.pathname, `?q=${addCharacterBetweenSpaceInString(suggestDivActiveKey[0].firstElementChild.innerHTML, ' ', '+')}&`, `cou=${getCountryAcronym(selectedCountry.innerHTML)}&`,`bg=${backgroundColor}`)
else //historyPushState
console.log(location.origin + location.pathname, `?q=${addCharacterBetweenSpaceInString(mainSearchInput.value, ' ', '+')}&`, `cou=${getCountryAcronym(selectedCountry.innerHTML)}&`,`bg=${backgroundColor}`)
mainSearch() mainSearch()
// if(!suggestMainInput.classList.contains('disable')) hideSuggestWords()
// return mainSearch()
} }
if(suggestMainInput.classList.contains('disable') || suggestMainInput.querySelectorAll('div').length === 0) return if(suggestMainInput.classList.contains('disable') || suggestMainInput.querySelectorAll('div').length === 0) return
if(suggestMainInput.querySelectorAll('div.active').length === 0 && (e.keyCode === 40 || e.keyCode === 38)) { if(suggestMainInput.querySelectorAll('div.active').length === 0 && (e.keyCode === 40 || e.keyCode === 38)) {
mainSearchInput.value = suggestDivs[place].firstElementChild.innerHTML mainSearchInput.value = suggestDivs[place].firstElementChild.innerHTML
return suggestDivs[place].classList.add('active') return suggestDivs[place].classList.add('active')
@ -654,7 +665,7 @@ searchCountriesInput.oninput = () => {
} }
function elementAdjustmentsSearchCountries(order) { function elementAdjustmentsSearchCountries(order) {
if(order == 'change') { if(order === 'change') {
document.querySelectorAll('#select-country > h6')[0].classList.add('disable') document.querySelectorAll('#select-country > h6')[0].classList.add('disable')
document.querySelectorAll('#select-country > h6')[1].classList.add('disable') document.querySelectorAll('#select-country > h6')[1].classList.add('disable')
listOfCountries.style.gridRow = '3/8' listOfCountries.style.gridRow = '3/8'
@ -669,6 +680,7 @@ let children = []
let hasChildren = [] let hasChildren = []
let noChildren = [] let noChildren = []
let clickOnOpenedElement let clickOnOpenedElement
const countryDivExceptions = [showCountriesLink, sclSpan, sclStrong]
function clickInOutCheck(parent, target) { function clickInOutCheck(parent, target) {
clickOnOpenedElement = false clickOnOpenedElement = false
@ -679,22 +691,14 @@ function clickInOutCheck(parent, target) {
children.shift() children.shift()
} }
if(parent === selectCountryDiv || parent === logInOptions){ if(checkIfClickIsOnElement(hasChildren, target) === true || checkIfClickIsOnElement(noChildren, target) === true) clickOnOpenedElement = true
if(target === overlay) clickOnOpenedElement = false
else clickOnOpenedElement = true
} else {
if(target.lastElementChild == document.querySelectorAll('script').lastElementChild) clickOnOpenedElement = true
else clickOnOpenedElement = false else clickOnOpenedElement = false
}
checkIfClickIsOnElement(hasChildren, target) if(clickOnOpenedElement === false && parent === extraSearchOptions && target !== extOptIcon) hideExtraSearchOptions()
checkIfClickIsOnElement(noChildren, target) else if(clickOnOpenedElement === false && parent === suggestMainInput) hideSuggestWords()
else if(clickOnOpenedElement === false && parent === extOptProfile) manageExtraProfileOptions()
if(clickOnOpenedElement == false && parent == extraSearchOptions) manageExtraSearchOptions() else if(clickOnOpenedElement === false && parent === selectCountryDiv && countryDivExceptions.some((val) => val === target) === false) hideSelectCountry()
else if(clickOnOpenedElement == false && parent == suggestMainInput) hideSuggestWords() else if(clickOnOpenedElement === false && parent === logInOptions && target !== loginButton) manageLoginOptions()
else if(clickOnOpenedElement == false && parent == extOptProfile) manageExtraProfileOptions()
else if(clickOnOpenedElement == false && parent == selectCountryDiv) hideSelectCountry()
else if(clickOnOpenedElement == false && parent == logInOptions) manageLoginOptions()
children = [] children = []
hasChildren = [] hasChildren = []
@ -708,7 +712,7 @@ function doesElementHaveChildren(parent) {
} }
else noChildren.push(parent) else noChildren.push(parent)
} }
function checkIfClickIsOnElement(array, target) { return array.filter(val => { return val === target}) } function checkIfClickIsOnElement(array, target) { return array.some(val => { return val === target}) }
exactPhrase.oninput = () => { inputExtraSearchOptionChange() } exactPhrase.oninput = () => { inputExtraSearchOptionChange() }
@ -770,17 +774,8 @@ async function fetchNewsArticles() {
// }) // })
const json = await response.json() const json = await response.json()
const articles = await json.articles const articles = await json.articles
console.log(articles, `http://cors-anywhere.herokuapp.com/http://newsapi.org/v2/everything?q=-velenje america "coronavirus"&sortBy=popularity&apiKey=${key}`)
} }
const information = {
firstName : 'Nik',
lastName : 'Topler'
}
let { firstName } = information
// console.log(firstName)
function createFormData(word) { function createFormData(word) {
let formData = new FormData let formData = new FormData
formData.append(word, '') formData.append(word, '')
@ -790,9 +785,5 @@ function capitalizeString(string) { return string.charAt(0).toUpperCase() + stri
function removeCharactersInString(string, frontNumber, backNumber) { return string.slice(frontNumber, backNumber)} function removeCharactersInString(string, frontNumber, backNumber) { return string.slice(frontNumber, backNumber)}
function removeDuplicates(array) { array.splice(0, array.length, ...(new Set(array))) } function removeDuplicates(array) { array.splice(0, array.length, ...(new Set(array))) }
function removeSelectedValuesFromArray(array, target) { return target.filter(val => !array.includes(val)) } function removeSelectedValuesFromArray(array, target) { return target.filter(val => !array.includes(val)) }
function addCharacterBetweenSpaceInString(word, replace, character) { function urlEdit(string) { return decodeURIComponent(string).trim().replace(/\s\s+/g, ' ') }
word = word.trim().replace(/\s\s+/g, ' ') // string.trim().replace(/\s\s+/g, ' ').replace(/%20/g, ' ').replace(/%22/g, '"')
if(replace === ' ') return word.replace(/\s/g, character)
else if(replace === '+') return word.replace(/\+/g, character)
}

View file

@ -25,17 +25,21 @@ function checkWindowWidth900() {
function manageExtraSearchOptions() { function manageExtraSearchOptions() {
if(extraSearchOptions.classList.contains('disable')) { if(extraSearchOptions.classList.contains('disable')) {
hideSuggestWords() hideSuggestWords()
showExtraSearchOptions()
} else hideExtraSearchOptions()
}
function showExtraSearchOptions() {
extraSearchOptions.classList.remove('disable') extraSearchOptions.classList.remove('disable')
mainSearchInput.style.borderBottomLeftRadius = '0' mainSearchInput.style.borderBottomLeftRadius = '0'
mainSearchInput.style.borderBottomRightRadius = '0' mainSearchInput.style.borderBottomRightRadius = '0'
extOptIcon.style.transform = 'rotate(180deg)' extOptIcon.style.transform = 'rotate(180deg)'
if(!indexTimeSelect.classList.contains('disable')) indexTimeSelect.classList.add('disable') if(!indexTimeSelect.classList.contains('disable')) indexTimeSelect.classList.add('disable')
} else { }
function hideExtraSearchOptions() {
extraSearchOptions.classList.add('disable') extraSearchOptions.classList.add('disable')
mainSearchInput.style.borderBottomLeftRadius = '6px' mainSearchInput.style.borderBottomLeftRadius = '6px'
mainSearchInput.style.borderBottomRightRadius = '6px' mainSearchInput.style.borderBottomRightRadius = '6px'
extOptIcon.style.transform = 'rotate(0deg)' extOptIcon.style.transform = 'rotate(0deg)'
}
} }
function resetExtraSearchOptions() { function resetExtraSearchOptions() {
indexTimeLabel.innerHTML = 'Anytime' indexTimeLabel.innerHTML = 'Anytime'

View file

@ -1,113 +1,101 @@
// /** Google */ // // /** Google */
function onSignIn(googleUser) {
console.log('Logged in as: ' + JSON.stringify(googleUser.getBasicProfile()))
let profile = googleUser.getBasicProfile() // let googleUser = {}
// console.log('ID: ' + profile.getId()) // Do not send to your backend! Use an ID token instead. // function startApp() {
// console.log('Name: ' + profile.getName()) // gapi.load('auth2', () => {
// console.log('Image URL: ' + profile.getImageUrl()) // auth2 = gapi.auth2.init({
// console.log('Email: ' + profile.getEmail()) // client_id: '571327981909-r5sunoo4l6uqducmqm7vjon1af0tmso1.apps.googleusercontent.com',
} // cookiepolicy: 'single_host_origin',
// })
function onFailure(error) { // attachSignin(document.getElementById('googleBtn'))
console.log(error) // })
} // }
var googleUser = {}; // function attachSignin(element) {
var startApp = function() { // auth2.attachClickHandler(element, {},
gapi.load('auth2', function(){ // (googleUser) => {
auth2 = gapi.auth2.init({ // console.log(googleUser.getBasicProfile())},
client_id: '571327981909-r5sunoo4l6uqducmqm7vjon1af0tmso1.apps.googleusercontent.com', // (error) => {
cookiepolicy: 'single_host_origin', // alert(JSON.stringify(error, undefined, 2))
}); // })
attachSignin(document.getElementById('googleBtn')); // }
}); // startApp()
}; // function signOut() {
function attachSignin(element) { // let auth2 = gapi.auth2.getAuthInstance()
auth2.attachClickHandler(element, {}, // auth2.signOut().then(function () {
(googleUser) =>{ // console.log('User signed out.')
console.log(googleUser.getBasicProfile())}, // })
(error) => { // }
// alert(JSON.stringify(error, undefined, 2));
});
}
startApp()
function signOut() {
var auth2 = gapi.auth2.getAuthInstance()
auth2.signOut().then(function () {
console.log('User signed out.')
})
}
/** GitHub */ // /** GitHub */
document.getElementById('github-button').addEventListener('click', () => { // document.getElementById('github-button').addEventListener('click', () => {
// Initialize with your OAuth.io app public key // // Initialize with your OAuth.io app public key
OAuth.initialize('_nPRfzTNGplyDCW0vD9dmek5QAg'); // OAuth.initialize('_nPRfzTNGplyDCW0vD9dmek5QAg');
// Use popup for oauth // // Use popup for oauth
// Alternative is redirect // // Alternative is redirect
OAuth.popup('github').then(github => { // OAuth.popup('github').then(github => {
console.log('github:', github); // console.log('github:', github);
// Retrieves user data from oauth provider // // Retrieves user data from oauth provider
// Prompts 'welcome' message with User's email on successful login // // Prompts 'welcome' message with User's email on successful login
// #me() is a convenient method to retrieve user data without requiring you // // #me() is a convenient method to retrieve user data without requiring you
// to know which OAuth provider url to call // // to know which OAuth provider url to call
github.me().then(data => { // github.me().then(data => {
console.log('me data:', data); // console.log('me data:', data);
// alert('GitHub says your email is:' + data.email + ".\nView browser 'Console Log' for more details"); // // alert('GitHub says your email is:' + data.email + ".\nView browser 'Console Log' for more details");
}); // });
// Retrieves user data from OAuth provider by using #get() and // // Retrieves user data from OAuth provider by using #get() and
// OAuth provider url // // OAuth provider url
github.get('/user').then(data => { // github.get('/user').then(data => {
console.log('self data:', data); // console.log('self data:', data);
}) // })
}); // });
}) // })
// /** FaceBook */ // // /** FaceBook */
// // function statusChangeCallback(response) { // Called with the results from FB.getLoginStatus(). // // // function statusChangeCallback(response) { // Called with the results from FB.getLoginStatus().
// // console.log('statusChangeCallback'); // // // console.log('statusChangeCallback');
// // console.log(response); // The current login status of the person. // // // console.log(response); // The current login status of the person.
// // if (response.status === 'connected') { // Logged into your webpage and Facebook. // // // if (response.status === 'connected') { // Logged into your webpage and Facebook.
// // testAPI(); // // // testAPI();
// // } else { // Not logged into your webpage or we are unable to tell. // // // } else { // Not logged into your webpage or we are unable to tell.
// // document.getElementById('status').innerHTML = 'Please log ' + // // // document.getElementById('status').innerHTML = 'Please log ' +
// // 'into this webpage.'; // // // 'into this webpage.';
// // } // // // }
// // } // // // }
// // function checkLoginState() { // Called when a person is finished with the Login Button. // // // function checkLoginState() { // Called when a person is finished with the Login Button.
// // FB.getLoginStatus(function(response) { // See the onlogin handler // // // FB.getLoginStatus(function(response) { // See the onlogin handler
// // statusChangeCallback(response); // // // statusChangeCallback(response);
// // }); // // // });
// // } // // // }
// // window.fbAsyncInit = function() { // // // window.fbAsyncInit = function() {
// // FB.init({ // // // FB.init({
// // appId : '1318555625202480', // // // appId : '1318555625202480',
// // cookie : true, // Enable cookies to allow the server to access the session. // // // cookie : true, // Enable cookies to allow the server to access the session.
// // xfbml : true, // Parse social plugins on this webpage. // // // xfbml : true, // Parse social plugins on this webpage.
// // version : '' // Use this Graph API version for this call. // // // version : '' // Use this Graph API version for this call.
// // }); // // // });
// // FB.getLoginStatus(function(response) { // Called after the JS SDK has been initialized. // // // FB.getLoginStatus(function(response) { // Called after the JS SDK has been initialized.
// // statusChangeCallback(response); // Returns the login status. // // // statusChangeCallback(response); // Returns the login status.
// // }); // // // });
// // }; // // // };
// // function testAPI() { // Testing Graph API after login. See statusChangeCallback() for when this call is made. // // // function testAPI() { // Testing Graph API after login. See statusChangeCallback() for when this call is made.
// // console.log('Welcome! Fetching your information.... '); // // // console.log('Welcome! Fetching your information.... ');
// // FB.api('/me', function(response) { // // // FB.api('/me', function(response) {
// // console.log('Successful login for: ' + response.name); // // // console.log('Successful login for: ' + response.name);
// // document.getElementById('status').innerHTML = // // // document.getElementById('status').innerHTML =
// // 'Thanks for logging in, ' + response.name + '!'; // // // 'Thanks for logging in, ' + response.name + '!';
// // }); // // // });
// // } // // // }

View file

@ -40,10 +40,11 @@
const submitButton = document.getElementById('extraOptionsSearchButton') const submitButton = document.getElementById('extraOptionsSearchButton')
const date = document.getElementById('extra-option-select') const date = document.getElementById('extra-option-select')
/** Navigation Bar Right */
const loginButton = document.getElementById('login-button')
/** Extra Search Options */ /** Extra Search Options */
let indexTimeSelect = document.getElementById('index-time-select') const indexTimeSelect = document.getElementById('index-time-select')
let indexTimeLabel = document.getElementById('index-time-label') const indexTimeLabel = document.getElementById('index-time-label')
/* Navigation Bar Right */ /* Navigation Bar Right */
const logInOptions = document.getElementById('login-option-div') const logInOptions = document.getElementById('login-option-div')
@ -62,6 +63,9 @@
const sideBarAboutContent = document.getElementById('about-sidebar-content') const sideBarAboutContent = document.getElementById('about-sidebar-content')
const mainContentContainer = document.getElementById('main-content-container') const mainContentContainer = document.getElementById('main-content-container')
let mainContentHeader = document.getElementById('main-content-header') let mainContentHeader = document.getElementById('main-content-header')
const showCountriesLink = document.getElementById('show-countries-button')
const sclSpan = showCountriesLink.firstElementChild
const sclStrong = showCountriesLink.lastElementChild
const overlay = document.getElementById('overlay') const overlay = document.getElementById('overlay')

View file

@ -13,8 +13,8 @@
<script src="../JS/variables.js" defer></script> <script src="../JS/variables.js" defer></script>
<script src="../JS/show.js" defer></script> <script src="../JS/show.js" defer></script>
<script src="../JS/main.js" defer></script>
<script src="..JS/diacritics.js" defer></script> <script src="..JS/diacritics.js" defer></script>
<script src="../JS/main.js" defer></script>
<script src="../JS/sign.js" defer></script> <script src="../JS/sign.js" defer></script>
<script src="https://kit.fontawesome.com/89923351fd.js" crossorigin="anonymous" defer></script> <script src="https://kit.fontawesome.com/89923351fd.js" crossorigin="anonymous" defer></script>

View file

@ -15,7 +15,7 @@
placeholder="Search for latest news articles" autocomplete="off" value=""> placeholder="Search for latest news articles" autocomplete="off" value="">
<figure class="search-icon-figure flex align-center justify-center relative" id="search-icon-figure"> <figure class="search-icon-figure flex align-center justify-center relative" id="search-icon-figure">
<a href="#" class="search-icon flex align-center justify-center border-radius-50" <a href="#" class="search-icon flex align-center justify-center border-radius-50"
id="main-search-icon-a" onclick="mainSearch()"> id="main-search-icon-a" onclick="mainSearch(undefined,'main-input')">
<i class="far fa-search" id="main-search-icon"></i> <i class="far fa-search" id="main-search-icon"></i>
<i class="far fa-arrow-left back-icon disable" id="main-search-icon-back-left"></i> <i class="far fa-arrow-left back-icon disable" id="main-search-icon-back-left"></i>
</a> </a>

View file

@ -13,6 +13,7 @@
<script src="JS/variables.js" defer></script> <script src="JS/variables.js" defer></script>
<script src="JS/show.js" defer></script> <script src="JS/show.js" defer></script>
<script src="JS/diacritics.js" defer></script>
<script src="JS/main.js" defer></script> <script src="JS/main.js" defer></script>
<script src="JS/sign.js" defer></script> <script src="JS/sign.js" defer></script>

View file

@ -33,9 +33,105 @@
<section class="main-content-section single" id="main-content-section"> <section class="main-content-section single" id="main-content-section">
<div class="main-content-container"> <div class="main-content-container">
<div class="article-container"> <div class="article-container">
<article> <article></article>
<article></article>
</article> <article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
<article></article>
</div> </div>
<aside id="main-side-content-container"> <aside id="main-side-content-container">
<article class="search aside"> <article class="search aside">
@ -102,8 +198,6 @@
<hr> <hr>
<span class="or-login absolute">or</span> <span class="or-login absolute">or</span>
<figure class="x-icon absolute flex align-center justify-center border-radius-50"> <figure class="x-icon absolute flex align-center justify-center border-radius-50">
<i class="fal fa-times fa-lg pointer" onclick="manageLoginOptions()"></i> <i class="fal fa-times fa-lg pointer" onclick="manageLoginOptions()"></i>
</figure> </figure>