How can I add the link to the image or ttitle? - javascript

I am trying to add the link on the image or title. when I click on the image/text it should take me to another page index.html.
How can I do that?
const apiUrl = 'https://api.themoviedb.org/3/discover/movie
sort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1;
const IMGPATH = "https://image.tmdb.org/t/p/w1280";
const SEARCHAPI = "https://api.themoviedb.org/3/search/movie?
&api_key=04c35731a5ee918f014970082a0088b1&query=";
const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");
showMovies(apiUrl);
function showMovies(url){
fetch(url).then(res => res.json())
.then(function(data){
console.log(data.results);
data.results.forEach(element => {
const el = document.createElement('div');
const image = document.createElement('img');
const text = document.createElement('h2');
text.innerHTML = `${element.title}`;
image.src = IMGPATH + element.poster_path;
el.appendChild(image);
el.appendChild(text);
main.appendChild(el);
});
});
}
form.addEventListener("submit", (e) => {
e.preventDefault();
main.innerHTML = '';
const searchTerm = search.value;
if (searchTerm) {
showMovies(SEARCHAPI + searchTerm);
search.value = "";
}
});

Fixed your code, the tick was to add a element instead of with the desired href
const apiUrl =
"https://api.themoviedb.org/3/discover/moviesort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1";
const IMGPATH = "https://image.tmdb.org/t/p/w1280";
const SEARCHAPI =
"https://api.themoviedb.org/3/search/movie? &api_key=04c35731a5ee918f014970082a0088b1&query=";
const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");
showMovies(apiUrl);
function showMovies(url) {
fetch(url)
.then((res) => res.json())
.then(function (data) {
console.log(data.results);
data.results.forEach((element) => {
el = document.createElement("a");
el.href = "https://example.com"
const image = document.createElement("img");
const text = document.createElement("h2");
text.innerHTML = `${element.title}`;
image.src = IMGPATH + element.poster_path;
el.appendChild(image);
el.appendChild(text);
main.appendChild(el);
});
});
}
form.addEventListener("submit", (e) => {
e.preventDefault();
main.innerHTML = "";
const searchTerm = search.value;
if (searchTerm) {
showMovies(SEARCHAPI + searchTerm);
search.value = "";
}
});

Related

fetch image from URL Javascript

How I can make this
var imageurl = 'https://tr.wikipedia.org/wiki/'
let queryimage = `${imageurl}Dosya:${cityName}.jpg`
console.log(queryimage)
When ı look console ı see this ;
https://tr.wikipedia.org/wiki/Dosya:england.jpg
thats ok but now
How ı can download image on this page https://tr.wikipedia.org/wiki/Dosya:england.jpg
This is your way :
// Your url must be like this : 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/England.jpg/800px-England.jpg'
let cityName = 'England';
let imageurl = 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/'
let queryimage = `${imageurl}${cityName}.jpg/800px-${cityName}.jpg`
let img = document.getElementById('image');
img.setAttribute('src',queryimage)
You can use MediaWiki's Action API to retrieve information about the images in these pages and grab the source of this image.
async function grabImageInfo(pageTitle) {
const resp = await fetch(`https://tr.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=${pageTitle}&piprop=original&format=json&origin=*`);
if (!resp.ok) {
throw new Error("Network Error");
}
return resp.json();
}
async function grabImageSource(pageTitle) {
const imageInfo = await grabImageInfo(pageTitle);
return Object.values(imageInfo.query.pages)[0].original.source;
}
const select = document.querySelector("select");
const img = document.querySelector("img");
const a = document.querySelector("a");
async function handleChange() {
try {
const pageTitle = `Dosya:${select.value}.jpg`;
const imgUrl = await grabImageSource(pageTitle);
img.src = imgUrl;
a.href = `https://tr.wikipedia.org/wiki/${pageTitle}`
}
catch(err) {
console.error(err);
}
}
select.onchange = handleChange;
handleChange();
<select>
<option>England</option>
<option>Italy</option>
<option>Germany</option>
<option>Flower</option>
<option>Cat</option>
</select><br>
<a>Go to Wikipedia's page</a><br>
<img>

add async await to fetch javascript

I'm new to async and await. I'm working on a recipe website using an api and fetch. need help to add async await to the fetch. I'm using spoonacular api.
there are no errors just want to add async await.
function retrieve(e) {
newsList.innerHTML = "";
e.preventDefault();
const apiKey = "my api key";
let topic = input.value;
let url = `https://api.spoonacular.com/recipes/complexSearch?query=${topic}&apiKey=${apiKey}&cuisine=&fillIngredients=false&addRecipeInformation=true&maxReadyTime=120&ignorePantry=flase&number=20&intolerances=gluten&sourceUrl=http://www.foodista.com`;
fetch(url)
.then((res) => {
return res.json();
})
.then((data) => {
console.log(data);
data.results.forEach((results) => {
let li = document.createElement("li");
let a = document.createElement("a");
let div = document.createElement("div");
let img = document.createElement("img");
let btn = document.createElement("button");
// styling
div.className = "newsdiv";
img.className = "newsimg";
btn.className = "btns";
li.style.width = "300px";
a.setAttribute("href", results.sourceUrl);
a.setAttribute("target", "_blank");
img.setAttribute("src", results.image);
div.textContent = results.title;
// btn.prepend(br);
div.appendChild(a);
div.prepend(img);
li.prepend(div);
btn.textContent = "Get Recipe";
div.appendChild(btn);
a.appendChild(btn);
newsList.appendChild(li);
});
})
.catch((error) => {
console.log(error);
});
}
Look at below snippet. This will be useful to your solution. In the function you may do whatever operations you want.
const retrieve = async (e) => {
newsList.innerHTML = "";
e.preventDefault();
const apiKey = "my api key";
let topic = input.value;
let url = `https://api.spoonacular.com/recipes/complexSearch?query=${topic}&apiKey=${apiKey}&cuisine=&fillIngredients=false&addRecipeInformation=true&maxReadyTime=120&ignorePantry=flase&number=20&intolerances=gluten&sourceUrl=http://www.foodista.com`;
const response = await fetch(url);
const myJson = await response.json(); //extract JSON from the http response
console.log(myjson);
}
retrieve(null);

How to trigger any event for dynamic element?

I have this one:
function fillCard()
{
const persons = document.getElementsByClassName("fillCard");
if(persons !== null)
{
for (var i = 0; i < persons.length; i++)
{
persons[i].addEventListener("click", function(event){
event.preventDefault();
var getUrl = this.getAttribute("href");
var url = new URL(location.origin + getUrl);
var Id = url.searchParams.get("id");
fetch(getUrl + "&id=" + Id + "&do=fillCard")
.then(response => response.json())
.then(data => {
document.getElementById("frm-newCard-lastname").value = data[0];
document.getElementById("frm-newCard-firstname").value = data[1];
document.getElementById("frm-newCard-dateofbirth").value = data[2];
document.getElementById("frm-newCard-phone_number").value = data[3];
document.getElementsByName("identifier")[0].value = data[4];
});
});
}
}
}
The problem is - those elements with class name fillCard are created dynamically by AJAX. The event listener does not work then. How to trigger the event properly? Thank you in advance for help.
Solution:
function fillCard()
{
document.addEventListener("click", function(e){
if(!e.target.matches('.fillCard'))
return;
e.preventDefault();
var getUrl = e.target.getAttribute("href");
var url = new URL(location.origin + getUrl);
var Id = url.searchParams.get("id");
fetch(getUrl + "&id=" + Id + "&do=fillCard")
.then(response => response.json())
.then(data => {
document.getElementById("frm-newCard-lastname").value = data[0];
document.getElementById("frm-newCard-firstname").value = data[1];
document.getElementById("frm-newCard-dateofbirth").value = data[2];
document.getElementById("frm-newCard-phone_number").value = data[3];
document.getElementsByName("identifier")[0].value = data[4];
});
});
}

Removing information from the URL string

I'm creating a chat but I was inspired by a source, when I "Log-In" and the chat appears, this appears in the URL:
chat.html?username=rr&room=JavaScript
How do I make sure that when I enter the chat it simply sees "Chat.html"?
I tried to add this code to it, but the problem would be the same if someone changed, it's like it's a GET. How do I do it in POST? It doesn't come easy with javascript
Code:
const chatForm = document.getElementById('chat-form');
const chatMessages = document.querySelector('.chat-messages');
const roomName = document.getElementById('room-name');
const userList = document.getElementById('users');
// Get username and room from URL
const { username, room } = Qs.parse(location.search, {
ignoreQueryPrefix: true,
});
const socket = io();
socket.emit('joinRoom', { username, room });
socket.on('roomUsers', ({ room, users }) => {
outputRoomName(room);
outputUsers(users);
});
socket.on('message', (message) => {
console.log(message);
outputMessage(message);
chatMessages.scrollTop = chatMessages.scrollHeight;
});
chatForm.addEventListener('submit', (e) => {
e.preventDefault();
let msg = e.target.elements.msg.value;
msg = msg.trim();
if (!msg) {
return false;
}
socket.emit('chatMessage', msg);
// Clear input
e.target.elements.msg.value = '';
e.target.elements.msg.focus();
});
// Output message to DOM
function outputMessage(message) {
const div = document.createElement('div');
div.classList.add('message');
const p = document.createElement('p');
p.classList.add('meta');
p.innerText = message.username;
p.innerHTML += `<span> - ${message.time}</span>`;
div.appendChild(p);
const para = document.createElement('p');
para.classList.add('text');
para.innerText = message.text;
div.appendChild(para);
document.querySelector('.chat-messages').appendChild(div);
}
function outputRoomName(room) {
roomName.innerText = room;
}
function outputUsers(users) {
userList.innerHTML = '';
users.forEach((user) => {
const li = document.createElement('li');
li.innerText = user.username;
userList.appendChild(li);
});
}
document.getElementById('leave-btn').addEventListener('click', () => {
const leaveRoom = confirm('Sei sicuro di voler uscire dalla chatroom?');
if (leaveRoom) {
window.location = '../index.html';
} else {
}
});
I hope I have explained myself well, I just need to add security to the website because then they could enter random "rooms", could I put the sessions?

Change Fetch URL from event listener?

I'm trying to change a global variable from inside a click event listener. However the variable fails to change once button is clicked. The objective here is to change a URL for a fetch request.
// Default URL
var url = 'https://newsapi.org/v2/top-headlines?sources=bbc-news&Apikey123';
var req = new Request(url);
// Event Listener - Change URL
document.getElementById('btn').addEventListener('click', function() {
var url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
var req = new Request(url);
sendRequest();
})
// Fetch Data from API
function sendRequest() {
fetch(req)
.then(r => r.json())
.then(r => {
const container = document.getElementsByClassName('post-container')[0];
for(i = 0; i < 5 ; i++) {
// Create post elements
const post = document.createElement('div');
const postHeader = document.createElement('div');
const postBody = document.createElement('div');
// Set ID
post.id = 'post';
postHeader.id = 'post-header';
postBody.id = 'post-body';
// Append Elements
container.appendChild(post);
post.appendChild(postHeader);
post.appendChild(postBody);
// Post title data from array into div
let article = r.articles[i];
let title = article.title;
let content = article.description;
postHeader.innerHTML = title;
postBody.innerHTML = content;
}
console.log(container);
});
}
sendRequest();
To solve the problem:
...
document.getElementById('btn').addEventListener('click', function() {
var url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
// Don't use var, becouse it's variable have scope in current function
// var req = new Request(url);
req = new Request(url);
sendRequest();
})
...
But better send param to sendRequest:
...
// Event Listener - Change URL
document.getElementById('btn').addEventListener('click', function() {
var url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
var req = new Request(url);
sendRequest(req); // <--- set param
})
// Fetch Data from API
function sendRequest(req) { // <--- get param
...
});
...
Remove the var from inside the Event Listener
document.getElementById('btn').addEventListener('click', function()
{
url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
var req = new Request(url);
sendRequest();
})
The thing is you are declaring the var url twice , and var req twice
the first one at the begining of your code and the second one in your event listner ,
try this
var url = 'https://newsapi.org/v2/top-headlines?sources=bbc-news&Apikey123';
var req = new Request(url);
// Event Listener - Change URL
document.getElementById('btn').addEventListener('click', function() {
url = 'https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=Apikey123';
req = new Request(url);
sendRequest();
})
// Fetch Data from API
function sendRequest() {
fetch(req)
.then(r => r.json())
.then(r => {
const container = document.getElementsByClassName('post-container')[0];
for(i = 0; i < 5 ; i++) {
// Create post elements
const post = document.createElement('div');
const postHeader = document.createElement('div');
const postBody = document.createElement('div');
// Set ID
post.id = 'post';
postHeader.id = 'post-header';
postBody.id = 'post-body';
// Append Elements
container.appendChild(post);
post.appendChild(postHeader);
post.appendChild(postBody);
// Post title data from array into div
let article = r.articles[i];
let title = article.title;
let content = article.description;
postHeader.innerHTML = title;
postBody.innerHTML = content;
}
console.log(container);
});
}
sendRequest();

Categories