Dynamically add google maps div into DOM - javascript

I'm wanting to add the Google Maps API div, <div id="map"></div> within a card that's dynamically added to the DOM, after a user has input a search. I'm able to append it the main div, as a test, but not within the card one I'm appending after the the card is inserted into the DOM.
Code is below.
const APIURL = 'https://restcountries.eu/rest/v2/name/'
const GOOGLE_MAPS_API = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyDhlU1KMTlTh4C__bTJBxbVA-s7wvQbO9E&callback=initMap'
const main = document.getElementById('main')
const form = document.getElementById('form')
const search = document.getElementById('search')
async function getCountryData(name) {
try {
const { data } = await axios.get(APIURL + name)
data.forEach(res => {
const countryData = res
addGMapsEl()
createCountryCard(countryData)
getLatLngPos(countryData)
} )
} catch (err) {
if(err.response.status == 404) {
createErrorCard('No countries found')
setTimeout(() => {
main.innerHTML = ''}
, 1500);
}
}
}
// Google Map API
function addGMapsEl() {
const script = document.createElement('script');
script.src = GOOGLE_MAPS_API;
script.defer = true;
document.head.appendChild(script);
const mapDiv = document.createElement('div')
mapDiv.id = 'map'
main.appendChild(mapDiv)
}
let map;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 51, lng: 9},
zoom: 7
});
}
function createCountryCard(country) {
const cardHTML = `
<div class="content-container">
<div class="card">
<div class="wrapper">
<div class="card-title">
<h2>${country.name}</h2>
<h4>Capital: ${country.capital}</h4>
<h5>Population: ${country.population.toLocaleString('en')}</h5>
</div>
<div class="card-image">
<img
src="${country.flag}"
alt="${country.name +'-flag'}"
/>
</div>
</div>
<div class="wrapper">
<div class="map-content">
</div>
<div class="card-content">
<ul class="card-list">
<li><strong>Region:</strong> ${country.region}</li>
<li><strong>Subregion:</strong> ${country.subregion}</li>
<li><strong>Currency:</strong> ${country.currencies[0].name}<span> ${country.currencies[0].symbol}</span></li>
<li><strong>Spoken Language:</strong> ${country.languages[0].name}</li>
<li><strong>Timezone:</strong> ${country.timezones}</li>
</ul>
</div>
</div>
</div>
</div>
`
main.innerHTML += cardHTML
}
// Creates error card after no results found
function createErrorCard(msg) {
const cardHTML = `
<div class="card">
<h1>${msg}</h1>
</div>
`
main.innerHTML = cardHTML
}
// Clears the DOM on search
function clearDOM() {
main.innerHTML = ''
}
// Search Input
form.addEventListener('submit', (e) => {
e.preventDefault()
clearDOM()
const countryName = search.value
if(countryName) {
getCountryData(countryName)
search.value = ''
}
})
<body>
<div class="search-container">
<form id="form" class="form">
<input type="text" id="search" placeholder="Search for country..." />
</form>
</div>
<main id="main"></main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="script.js"></script>
</body>

Ok - so - to create a MAP you need to use new google.maps.Map( ELEMENT_TO_CONTAIN_THE_MAP, MAP_OPTIONS) which is in your mapInit func.
You should also load the API only once - so i moved things a little bit in your code...
I have removed the callback=initMap from your maps url - because your element doesn't exist in the DOM at the moment when google's script is loaded.
Then placed the call to mapInit after your createCountryCard call - because it adds your map element to the DOM - and now we can place the map within it.
Given your element the id argument <div class="map-content" id="map-content">. And then changed the id in mapInit function to match your elements id which is map-content.
const APIURL = 'https://restcountries.eu/rest/v2/name/'
const GOOGLE_MAPS_API = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyDhlU1KMTlTh4C__bTJBxbVA-s7wvQbO9E'
const main = document.getElementById('main')
const form = document.getElementById('form')
const search = document.getElementById('search')
async function getCountryData(name) {
try {
const {
data
} = await axios.get(APIURL + name)
data.forEach(res => {
const countryData = res
//gmaps element is on card
createCountryCard(countryData);
initMap();
getLatLngPos(countryData)
})
} catch (err) {
if (err.response.status == 404) {
createErrorCard('No countries found')
setTimeout(() => {
main.innerHTML = ''
}, 1500);
}
}
}
// Google Map API
function addGMapsEl() {
const script = document.createElement('script');
script.src = GOOGLE_MAPS_API;
script.defer = true;
document.head.appendChild(script);
const mapDiv = document.createElement('div')
mapDiv.id = 'map'
main.appendChild(mapDiv)
}
let map;
function initMap() {
map = new google.maps.Map(document.getElementById("map-content"), {
center: {
lat: 51,
lng: 9
},
zoom: 7
});
}
function createCountryCard(country) {
const cardHTML = `
<div class="content-container">
<div class="card">
<div class="wrapper">
<div class="card-title">
<h2>${country.name}</h2>
<h4>Capital: ${country.capital}</h4>
<h5>Population: ${country.population.toLocaleString('en')}</h5>
</div>
<div class="card-image">
<img
src="${country.flag}"
alt="${country.name +'-flag'}"
/>
</div>
</div>
<div class="wrapper">
<div id="map-content" class="map-content">
</div>
<div class="card-content">
<ul class="card-list">
<li><strong>Region:</strong> ${country.region}</li>
<li><strong>Subregion:</strong> ${country.subregion}</li>
<li><strong>Currency:</strong> ${country.currencies[0].name}<span> ${country.currencies[0].symbol}</span></li>
<li><strong>Spoken Language:</strong> ${country.languages[0].name}</li>
<li><strong>Timezone:</strong> ${country.timezones}</li>
</ul>
</div>
</div>
</div>
</div>
`
main.innerHTML += cardHTML
}
// Creates error card after no results found
function createErrorCard(msg) {
const cardHTML = `
<div class="card">
<h1>${msg}</h1>
</div>
`
main.innerHTML = cardHTML
}
// Clears the DOM on search
function clearDOM() {
main.innerHTML = ''
}
// Search Input
form.addEventListener('submit', (e) => {
e.preventDefault()
clearDOM()
const countryName = search.value
if (countryName) {
getCountryData(countryName)
search.value = ''
}
})
addGMapsEl();
.map-content {
width: 100%;
height: 300px;
}
.card-image img {
max-height: 50px;
box-shadow: 1px 1px 5px #aaa;
}
<body>
<div class="search-container">
<form id="form" class="form">
<input type="text" id="search" placeholder="Search for country..." />
</form>
</div>
<main id="main"></main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="script.js"></script>
</body>
Looks like it works now ...you probably want to use setCenter on yor map later to move the view to the new location - do it after mapInit
Added some CSS also - to give a size for the map element and shrink that huge flag you had.

I can see the url in your constant is wrong ... the correct one will be :
'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap'
Another thing you never call addGMapsEl() function to initialize the map.
Finally the .card-content element isn't presented on DOM.
To present the country on map you should create an event to handle that
$(document).on("input", "#search", function(e){
//handle input information here
})

Related

How to refresh page after filtering or mapping in javascript

I need to create a contact list with data from an API of random people. My page has a simple form (input + button) then after click should show a new list or filtered data from last list if there is some input text. The data is being fetch correctly and recorded into localStorage (limited to 10 users).
The problem: data is being added to the page instead of refreshing into the page.
How can I have new data on page for every click?
async function fetchPeople() {
const URL = 'https://randomuser.me/api/?results=10';
const res = await fetch(URL);
let data = await res.json();
return data;
}
async function data(name) {
let filteredData = [];
if (name.length > 0) {
let newdata = JSON.parse(localStorage.getItem('contacts'));
filteredData = newdata.filter((contact) => {
return contact.name.first.toLowerCase().includes(name);
});
} else {
let data = await fetchPeople();
localStorage.setItem('contacts', JSON.stringify(data.results));
filteredData = data.results;
return filteredData;
}
return filteredData;
}
async function printData() {
let ul = document.querySelector('#cards');
let name = document.querySelector('#contact').value.toLowerCase();
let filteredData = [];
filteredData = await data(name);
filteredData.forEach((contact) => {
let li = document.createElement('li');
li.innerHTML = `
<div class="card">
<img src="${contact.picture.large}"
alt="${contact.name.first} ${contact.name.last}"
class="card__image">
<h2 class="card__name">${contact.name.first} ${contact.name.last}</h2>
<p class="card__email">${contact.email}</p>
<p class="card__location">${contact.location.city}-${contact.location.state}</p>
<button class="card__btn">${contact.location.country}</button>
</div>`;
ul.appendChild(li);
});
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<section class="form">
<div class="search">
<h1>Contact List</h1>
<div class='search__field'>
<input type="text" name="contact" id="contact" placeholder="Nome do contato" class="search__name form-control">
<button type="button" onclick='printData()' class='btn btn-primary search__btn'>Search</button>
</div>
</div>
</section>
<section class="results">
<ul class="cards" id="cards"></ul>
</section>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
JSFiffle
https://jsfiddle.net/w7gknc2t/
You need to clear ul innerHTML before appending new data.
async function printData() {
let ul = document.querySelector('#cards');
let name = document.querySelector('#contact').value.toLowerCase();
let filteredData = [];
filteredData = await data(name);
ul.innerHTML = '';
filteredData.forEach((contact) => {
let li = document.createElement('li');
li.innerHTML = `
<div class="card">
<img src="${contact.picture.large}"
alt="${contact.name.first} ${contact.name.last}"
class="card__image">
<h2 class="card__name">${contact.name.first} ${contact.name.last}</h2>
<p class="card__email">${contact.email}</p>
<p class="card__location">${contact.location.city}-${contact.location.state}</p>
<button class="card__btn">${contact.location.country}</button>
</div>`;
ul.appendChild(li);
});
}

How to add an image from a template form with JS?

i'm studying JS and at the moment i'm not really good with it. I created a page (a kind of social network) and i need to add an image from an URL when i fill a form. The form has 2 fields: Image title and URL
the initial cards that i have on the page, i handle to insert them from an array. But i can't understand how to add a single photo from a form.
The new photo should appear as first image, the previous 1st image should be at the 2nd place and so on, cards can be deleted when i click on a button but i didn't really got how to do it, and the like buttons should work for every single cards... i've was looking for it on google and i found some stuffs but they didn't work for me.
how can i solve it?
my code:
HTML
<section class="cards" id="cards">
<!-- images will be added here-->
<div class="cards__add-form-overlay">
<form class="cards__add-form">
<button class="cards__add-form-close-icon"></button>
<p class="cards__add-form-text">New place</p>
<input type="text" placeholder="Name" class="cards__add-form-first-field" id="ImageName" value= "">
<input type="text" placeholder="Image URL" class="cards__add-form-second-field" id="URL" value= "">
<button type="submit" class="cards__add-form-submit">create</button>
</form>
</div>
</section>
<template class="elements" id="elements">
<div class="element">
<div class="element__card">
<img class="element__photo" src="" alt="">
<div class="element__button-container">
<button type="button" class="element__trash-button" id="trashbutton">
</div>
<div class="element__text">
<p class="element__place"></p>
<button type="button" class="element__like-button" id="likebutton" onclick="toggle()"></button>
</div>
</div>
</template>
<script type="text/javascript" src="./script.js"></script>
</body>
</html>
JS
// IMAGES //
// description: adding photos in the page from an array with JS //
const initialCards = [
{ name:'', link:''},
{ name:'', link:''},
{ name:'', link:''},
{ name:'', link:''},
{ name:'', link:''},
{ name:'', link:''}
];
initialCards.forEach(card => cardItem(card));
function cardItem(cardData) {
const container = document.getElementById("cards");
const cardTemplate = document.getElementById("elements").content;
const newCard = cardTemplate.cloneNode(true);
const elementImage = newCard.querySelector('.element__photo');
const elementText = newCard.querySelector('.element__place');
elementImage.src = cardData.link;
elementText.textContent = cardData.name;
container.append(newCard);
}
----- Until here all good
// description: adding popup when clicking on + button, and close with X button //
document.querySelector('.profile__add-button').addEventListener('click', function () {
document.querySelector('.cards__add-form-overlay').style.visibility = 'visible';
});
document.querySelector('.cards__add-form-close-icon').addEventListener('click', function () {
document.querySelector('.cards__add-form-overlay').style.visibility = 'hidden';
});
document.querySelector('.cards__add-form-submit').addEventListener('click', function () {
document.querySelector('.cards__add-form-overlay').style.visibility = 'hidden';
});
document.querySelector('.profile__add-button').addEventListener('click', function () {
document.querySelector('.cards__add-form').style.visibility = 'visible';
});
document.querySelector('.cards__add-form-close-icon').addEventListener('click', function () {
document.querySelector('.cards__add-form').style.visibility = 'hidden';
});
document.querySelector('.cards__add-form-submit').addEventListener('click', function () {
document.querySelector('.cards__add-form').style.visibility = 'hidden';
});
// description: adding photo through popup with 2 fields, name and URL //
const addPhoto = document.querySelector('.cards__add-form');
const imageNameInput = document.querySelector('.cards__add-form-first-field');
const imageUrlInput = document.querySelector('.cards__add-form-first-field');
function handleAddCardFormSubmit(evt) {
evt.preventDefault();
const element = createCard(imageNameInput.value, imageUrlInput.value);
elements.prepend(element);
imageNameInput.value = '';
imageUrlInput.value = '';
closePopup(evt.target.closest('.cards__add-form'));
}
function createCard(name, link) {
const elementTemplate = document.querySelector('#element-template').content;
const element = elementTemplate.querySelector('.element').cloneNode(true);
const elementImage = element.querySelector('.element__photo');
const elementTitle = element.querySelector('.element__place');
elementImage.src = link;
elementTitle.textContent = name;
//like button//
const likeButton = element.querySelector('.element__like-button');
likeButton.addEventListener('click', () => likeButton.classList.toggle('element__like-button_active'));
//delete cards //
element.addEventListener('click', function (evt) {
if (evt.target.classList.contains('element__trash-button')) {
evt.currentTarget.remove();
}
if (evt.target.classList.contains('element__photo')) {
openImagePopup(name, link);
}
});
return element;
}
initialCards.forEach(({name, link}) => elements.append(createCard(name, link)));
with this code, the new image doesn't appear, about like button console says that toogle() is not defined, and delete button don't delete the image but no error in the console

JavaScript Error when submitting HTML form: Form is NULL [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
My Issue:
Please help me run this code as it should. I am getting a null form error when typing a City name in the place holder and I'm not sure why I am practicing this code from here: https://webdesign.tutsplus.com/tutorials/build-a-simple-weather-app-with-vanilla-javascript--cms-33893
/*SEARCH BY USING A CITY NAME (e.g. athens) OR A COMMA-SEPARATED CITY NAME ALONG WITH THE COUNTRY CODE (e.g. athens,gr)*/
const form = document.querySelector(".top-banner form");
const input = document.querySelector(".top-banner input");
const msg = document.querySelector(".top-banner .msg");
const list = document.querySelector(".ajax-section .cities");
/*SUBSCRIBE HERE FOR API KEY: https://home.openweathermap.org/users/sign_up*/
const apiKey = "f077e7d6167270fa866a36699ab528fe"; /*REPLACE THIS WITH YOUR API KEY FROM OPENWEATHERMAP.ORG*/
form.addEventListener("submit", e => {
e.preventDefault();
let inputVal = input.value;
//check if there's already a city
const listItems = list.querySelectorAll(".ajax-section .city");
const listItemsArray = Array.from(listItems);
if (listItemsArray.length > 0) {
const filteredArray = listItemsArray.filter(el => {
let content = "";
//athens,gr
if (inputVal.includes(",")) {
//athens,grrrrrr->invalid country code, so we keep only the first part of inputVal
if (inputVal.split(",")[1].length > 2) {
inputVal = inputVal.split(",")[0];
content = el
.querySelector(".city-name span")
.textContent.toLowerCase();
} else {
content = el.querySelector(".city-name").dataset.name.toLowerCase();
}
} else {
//athens
content = el.querySelector(".city-name span").textContent.toLowerCase();
}
return content == inputVal.toLowerCase();
});
if (filteredArray.length > 0) {
msg.textContent = `You already know the weather for ${
filteredArray[0].querySelector(".city-name span").textContent
} ...otherwise be more specific by providing the country code as well 😉`;
form.reset();
input.focus();
return;
}
}
//ajax here
const url = `https://api.openweathermap.org/data/2.5/weather?q=${inputVal}&appid=${apiKey}&units=metric`;
fetch(url)
.then(response => response.json())
.then(data => {
const {
main,
name,
sys,
weather
} = data;
const icon = `https://s3-us-west-2.amazonaws.com/s.cdpn.io/162656/${
weather[0]["icon"]
}.svg`;
const li = document.createElement("li");
li.classList.add("city");
const markup = `
<h2 class="city-name" data-name="${name},${sys.country}">
<span>${name}</span>
<sup>${sys.country}</sup>
</h2>
<div class="city-temp">${Math.round(main.temp)}<sup>°C</sup></div>
<figure>
<img class="city-icon" src="${icon}" alt="${
weather[0]["description"]
}">
<figcaption>${weather[0]["description"]}</figcaption>
</figure>
`;
li.innerHTML = markup;
list.appendChild(li);
})
.catch(() => {
msg.textContent = "Please search for a valid city 😩";
});
msg.textContent = "";
form.reset();
input.focus();
});
<!DOCTYPE html>
<html>
<head>
<script src="main.js"></script>
</head>
<body>
<div class="api">
<div class="container">🌞 This demo needs an OpenWeather API key to work. <a target="_blank" href="https://home.openweathermap.org/users/sign_up">Get yours here for free!</a>
</div>
</div>
<section class="top-banner">
<div class="container">
<h1 class="heading">Simple Weather App</h1>
<form>
<input type="text" placeholder="Search for a city" autofocus>
<button type="submit">SUBMIT</button>
<span class="msg"></span>
</form>
</div>
</section>
<section class="ajax-section">
<div class="container">
<ul class="cities"></ul>
</div>
</section>
<footer class="page-footer">
<div class="container">
</div>
<small>Made with <span>❤</span> by George Martsoukos
</small>
<li class="city">
<h2 class="city-name" data-name="...">
<span>...</span>
<sup>...</sup>
</h2>
<span class="city-temp">...<sup>°C</sup></span>
<figure>
<img class="city-icon" src="..." alt="...">
<figcaption>...</figcaption>
</figure>
</li>
</footer>
</body>
</html>
It's because your javascript code is executed before DOM is fully loaded.
So you have two choices, either move
<script src="main.js"></script> as the last item inside body (before </body>)
or place all your javascript code inside:
document.addEventListener("DOMContentLoaded", e =>
{
// your code here
});

Event listener isnot working in asynchronous js

I know why it shows error because due to asynchronous, button is not loaded yet. Is there any way to fix it? I cannot explain much in words. At the time window is loaded , there is no button because it appears only after clicking id. i tried to put all codes but stack overflow requires much explanation
This is my main js code. Fetch works and i didnot include all codes.
const controlMovie = async()=> {
const id = window.location.hash.replace('#', '');
if(id){
// new id
clearMovie();
state.control = new Control(id);
await state.control.getMovies();
UImovie(state.control);
}
return id;
};
const viewList = async()=>
{
const id = window.location.hash.replace('#', '');
state.view= new Control(id);
await state.view.getMovies();
UIlist(state.view);
}
['hashchange', 'load'].forEach(event => window.addEventListener(event, controlMovie));
document.querySelector('.add').addEventListener('click', viewList);
This is for UI js part
const UImovie = (info)=> {
const markup = `
<div class="img-fig">
<img src="${info.image}" alt="${info.title}" class="movie-img">
</div>
<div class="movie_details">
<br>
<h3 style="align-items: center; font-weight: bold;"> ${info.title}</h3>
<p>Writer: ${info.writer}</p>
<p>Released date: ${info.year}</p>
<p>Actors: ${info.actors} </p>
<p>imdbRating: ${info.rating}</p>
<p>Total seasons: ${info.seasons}</p>
<p style="font-style: italic; color: red; font-size: 16px;"> "${info.story}"</p>
<button class= "add">+ Add to watchlist</button>
</div>
</div>
`;
document.querySelector('.movies-result').insertAdjacentHTML('afterbegin', markup);
};
const UIlist = (UI)=> {
const markup = `
<h3> ${UI.title} <button class="icons"><ion-icon name="trash"></ion-icon></button></h3>
`;
document.querySelector('.lists').insertAdjacentHTML('afterbegin', markup);
}
As commented, based on the provided code, you are added .icons dynamically. but .addEventListener is being executed during pageload. Due to this, when its executed, there is no elements available on DOM and no listener is added.
You should try using HTMLElement objects instead:
const UIlist = (UI)=> {
const h3 = document.createElement('h3');
h3.innerText = UI.title;
const button = document.createElement('button');
const icon = document.createElement('ion-icon');
icon.setAttribute('name', 'trash');
button.append(icon);
button.classList.add('icons');
button.addEventListener('click', function() {
console.log('Button Clicked');
})
h3.append(button)
document.querySelector('.lists').insertAdjacentElement('afterbegin', h3);
}
UIlist( { title: 'Bla' } )
<div>
<div class='lists'></div>
</div>

javascript issue calling function after adding event listener

I am working on a wikipedia viewer (https://codepen.io/rwiens/pen/YLMwBa) which is almost done but I have 2 problems:
I cannot submit my search results when I press enter. I have added an event listener and can console.log "hello: but I cannot call the searchWiki function.
When I do a new search the results are appended to the bottom pf my old results.
I've searched the web for the last half day and am stuck. Any help would be appreciated.
<div class="container">
<div class="banner text-center align-items">
<h1>Wiki Search</h1>
<p>Search for articles on Wikipedia</p>
</div>
<form action="" class="text-center">
<input type="search" id="search-box" placeholder="Search Here">
<div class="buttons">
<input type="button" onclick="searchWiki()" id="search-
button" value="Search">
<input type="submit" value="Feel Lucky?">
</div>
</form>
<div class="articles">
<ul id="results">
</ul>
</div>
</div>
<script type="test/javascript">
const searchBox = document.getElementById('search-box');
const sButton = document.getElementById('search-button');
const results = document.getElementById('results');
window.onload = function() {
searchBox.focus();
};
const searchWiki = () => {
const keyword = searchBox.value;
fetch("https://en.wikipedia.org/w/api.php?
&origin=*&action=opensearch&search=" + keyword + "&limit=5", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ query: event.currentTarget.value })
})
.then(response => response.json())
.then((data) => {
console.log(data);
build(data);
});
}
const build = (data) => {
let title = data[1];
let description = data[2];
let url = data[3];
for(let x = 0; x < 5; x++){
console.log(title);
const item = `<a href="${url[x]}" target="#">
<li>
<h5>${title[x]}</h5>
<p>${description[x]}.</p>
</li>
</a>`;
results.insertAdjacentHTML("beforeend", item);
}
}
searchBox.addEventListener("keyup", function(event) {
if (event.key === "Enter") {
searchWiki;
}
});
</script>
You are not calling searchWiki as function. Call it like this searchWiki();
Also you need to remove the form tag. Because you have button type elements in it , it is by default submitting your form on enter press.
Also clear results div before appending new data like this
results.innerHTML = ""
for(let x = 0; x < 5; x++){
console.log(title);
const item = `<a href="${url[x]}" target="#">
<li>
<h5>${title[x]}</h5>
<p>${description[x]}.</p>
</li>
</a>`;
results.insertAdjacentHTML("beforeend", item);
}
Check updated codepen
when I put searchWiki I am still not calling the search unfortunately. also, when i add results.innerHTML = "" my search only comes back with one result.
You need to add an event listener for the form submit. In that you need to cancel the event ( event.preventDefault() ).
Empty your results as #NanditaAroraSharma pointed out (best before calling build function)
Solved it. Removed the form as it was trying to send me to another page.
<div class="text-center">
<input type="search" id="search-box" placeholder="Search Here">
<div class="buttons">
<input type="button" onclick="searchWiki()" id="search-
button" value="Search">
<input type="button"
onclick="location.href='https://en.wikipedia.org/wiki/Special:Random';"
value="Feel Lucky?">
</div>
for building the html i took part of it out of the for loop.
const build = (data) => {
let title = data[1];
let description = data[2];
let url = data[3];
results.innerHTML = "";
for(let x = 0; x < 5; x++){
console.log(title);
const item = `<a href="${url[x]}" target="#">
<li>
<h5>${title[x]}</h5>
<p>${description[x]}.</p>
</li>
</a>`;
results.innerHTML += item;
}
}

Categories

Resources