-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.js
95 lines (73 loc) · 2.74 KB
/
script.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//-- News api call
const API_KEY = "499d03534f224e8890dcd1f95376001c"
const url = "https://newsapi.org/v2/everything?q="
async function fetchData(query){
const res = await fetch(`${url}${query}&apiKey=${API_KEY}`)
const data = await res.json()
return data
}
fetchData("Climate").then(data => renderMain(data.articles))
//menu btn
let mobilemenu = document.querySelector(".mobile")
let menuBtn = document.querySelector(".menuBtn")
let menuBtnDisplay = true;
menuBtn.addEventListener("click",()=>{
mobilemenu.classList.toggle("hidden")
})
//render news
function renderMain(arr){
let mainHTML = ''
for(let i = 0 ; i < arr.length ;i++){
if(arr[i].urlToImage){
mainHTML += ` <div class="card">
<a href=${arr[i].url}>
<img src=${arr[i].urlToImage} lazy="loading" />
<h4>${arr[i].title}</h4>
<div class="publishbyDate">
<p>${arr[i].source.name}</p>
<span>•</span>
<p>${new Date(arr[i].publishedAt).toLocaleDateString()}</p>
</div>
<div class="desc">
${arr[i].description}
</div>
</a>
</div>
`
}
}
document.querySelector("main").innerHTML = mainHTML
}
const searchBtn = document.getElementById("searchForm")
const searchBtnMobile = document.getElementById("searchFormMobile")
const searchInputMobile = document.getElementById("searchInputMobile")
const searchInput = document.getElementById("searchInput")
searchBtn.addEventListener("submit",async(e)=>{
e.preventDefault()
console.log(searchInput.value)
const data = await fetchData(searchInput.value)
renderMain(data.articles)
})
searchBtnMobile.addEventListener("submit",async(e)=>{
e.preventDefault()
const data = await fetchData(searchInputMobile.value)
renderMain(data.articles)
})
async function Search(query){
const data = await fetchData(query)
renderMain(data.articles)
}
//--
let mobileMenu = document.querySelector(".mobile");
// Function to toggle the visibility of the mobile menu
function toggleMobileMenu() {
mobileMenu.classList.toggle("hidden");
}
// Add a click event listener to the mobile menu button to toggle the visibility of the mobile menu
document.querySelector(".mobile-menu-button").addEventListener("click", toggleMobileMenu);
// Function to close the mobile menu if the user clicks outside of the menu
document.addEventListener("click", function(event) {
if (event.target !== mobilemenu && !mobileMenu.contains(event.target)) {
mobileMenu.classList.add("hidden");
}
});