Fetching image/title in an API wth Javascript - javascript

So I'm trying to make an API call to fetch images and their titles but got suck shortly afterward.
I am trying to use forEach loop to loop through the API and find the URL of the images and their titles. I will then use CSS and HTML to display on my HTML page. How can I achieve this with my following code?
My Javascript file ( need help implementing/ refactoring)
let pictures = document.getElementById("container");
function getPhoto() {}
if (pictures) {
let URL = "https://jsonplaceholder.typicode.com/albums/2/photos";
fetch(URL)
.then((data) => data.json())
.then((photos) => {
photos.forEach((photo) => {
return `<div><img src ="${photo.url}" width="200px" height="200px/></div>`;
});
document.getElementById(
"item-count"
).innerHTML = `There are ${photos.length} photo(s) being shown`;
});
}
Here is my HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="../css/index.css">
<link rel="stylesheet" type="text/css" href="../css/signup.css">
<link rel="stylesheet" type="text/css" href="../css/home.css">
<script defer src="../js/homeScript.js"></script>
<title>Document</title>
</head>
<body>
<div class="container">
<nav class="nav-content">
<h1 class="nav-title">Shop<span>yee</span></h1>
<li class="nav-post">
Home
</li>
<li class="nav-post">
Post
</li>
<li class="nav-post">
View
</li>
<li>
Sign up
</li>
<li>
Login In
</li>
</nav>
<h1 id="item-count"></h1>
<div class="grid-container" id="container">
</div>
</div>
</body>
</html>
Here is my CSS using the grid system:
.grid-container{
display:grid;
grid-template-rows: repeat(4,1fr);
grid-template-columns: repeat(4,1fr);
grid-auto-rows: 1fr;
grid-auto-columns: 1fr;
gap:.25rem;
margin:4px;
width:100%
}

I cannot really get where are you exactly stuck, so if you could elaborate on what your problem is.
Also for refactoring:
I see you have opened and closed the getPhotos() function. You can write your fetch API call logic inside the function. Also, the logic to have UI should be put in another function and call getPhotos(). This could help in managing your code, by making it more modular and keeping everything inside specific functions to do a specific task.

Related

jQuery load executes but callback is not executed

I am kinda new to website development, so I am asking for some help on the matter. I have the following snippet of html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--CSS Styles -->
<link rel="stylesheet" href="../assets/css/styles.css"/>
</head>
<body>
<!--Navigation bar-->
<div id="nav-placeholder"></div>
<!--end of Navigation bar-->
</body>
<script src="../assets/js/navigation_bar.js" type="text/javascript", locator="about"></script>
</html>
It calls the navigation_bar.js script provided here
locator = document.currentScript.getAttribute('locator');
function changeActiveElement(element_id){
console.log("Called");
nav_element = document.getElementById("navigation");
for (i = 0; i < nav_element.length; i++) {
console.log(nav_element[i].id)
if(nav_element[i].id == element_id) document.getElementById(element_id).className = "active-nav-link";
else document.getElementById(element_id).className = "nav-link";
}
}
$(function()
{$("#nav-placeholder").load("/assets/html/nav.html", function(){
changeActiveElement(locator);
});}
);
whereas the nav.html file is here:
<nav>
<h1>Some name</h1>
<ul id="navigation" class="navigation">
<li><a id="about" href="/pages/about.html" class="nav-link">About</a></li>
<li><a id="compt" href="#compt" class="nav-link">Competences</a></li>
<li><a id="projects" href="#projects" class="nav-link">Projects</a></li>
<li><a id="contact" href="#contact" class="nav-link">Contact</a></li>
</ul>
<button class="burger-menu" id="burger-menu">
<ion-icon class="bars" name="menu-outline"></ion-icon>
</button>
</nav>
The scope of the snippet is to change the class of the a tags listed in the navigation element. The navigation bar is correctly loaded via $("#nav-placeholder").load("/assets/html/nav.html"), yet changeActiveElement function is never executed via the callback.
Can someone explain me this behaviour?
I tested your code and everything is working except that nav_element is not a list and therefore nav_element.length throws an error. You could use document.querySelectorAll("#navigation"); instead, which returns a node list of all selected elements. Although, I would not recommend doing a for loop on elements by id. Use classes to select the elements. Id is only for one element.

I want to delete all checked lists pressing the delete button but I don't know how

I'm learning Javascript and now I'm making to-do list.I've finished the basic one but I want to add the delete button which delete all the checked lists to my to-do list.
I've tried some ways that I came up with and they all failed and I cannot find the answer by googling.
How can I do this ? If there is someone who know, please teach me . I'd appreciated if you could show me how.
this is my code ↓ the error happened saying cannot read property 'parentElement' of null at Object.deleteAll
deleteAll: function() {
let taskListItem, checkBox, checkBoxParent;
for (i=0; i<this.taskListChildren.length; i++){
taskListItem = this.taskListChildren[i];
checkBox = taskListItem.querySelector('input[type = "checkbox"]:checked');
checkBoxParent = checkBox.parentElement;
checkBoxParent.remove();
}
document.getElementById('deleteChecked').addEventListener('click', () => {
tasker.deleteAll();
});
πŸ™
// this is my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To Do List</title>
<link rel="stylesheet" href="css/styles.css">
<link href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" rel="stylesheet">
</head>
<body onLoad = "tasker.construct();">
<div class="tasker" id="tasker">
<div class="error" id="error">Please enter a task</div>
<div class="tasker-header" id="tasker-header">
<input type="text" id="input-task" placeholder ="Enter a task">
<button id="add-task-btn"><i class="fas fa-plus"></i></button>
</div>
<div class="tasker-body">
<ul id="tasks">
</ul>
</div>
<button id="deleteChecked">Delete</button>
</div>
<script src="js/main.js"></script>
</body>
</html>
You can use the jQuery library and solve it as follows.
Step 1) Define in your html button element:
<button id="button" onclick="reset()"> RESET </button>
Step 2) define the 'reset ()' function, like this
function reset()
{
$("input:chceckbox").removeAttr("chcecked");
}
Good luck!!

forEach method not setting style property for list items

Here is app.js
const listItems=document.querySelector(".student-list").children;
const numberOfItems=10;
const page=document.querySelector(".page");
displayPage=(list,pageNumber)=> {
const SI=(pageNumber*numberOfItems)-numberOfItems
const EI=pageNumber*numberOfItems
Array.of(list).forEach((item,index)=> {
if (index>= SI && index<EI) {
item.style.display="block";
} else {
item.style.display="none";
}
})
}
addPaginationLinks=(list)=> {
const pages=list.length/10
let html=``
for (let i=0; i<pages; i++) {
html+=`
<li>
<a class="active" href="#">${i+1}</a>
</li>`
return html
}
ul=document.createElement("UL");
ul.innerHTML=html;
div=document.createElement("DIV");
div.className.add("pagination");
div.appendChild(ul);
page.appendChild(div);
}
displayPage(listItems, 1);
addPaginationLinks(listItems);
Here is a sample of index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Students</title>
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/design.css">
</head>
<body>
<div class="page">
<div class="page-header cf">
<h2>Students</h2>
<!-- dynamically insert search form here (optional) -->
</div>
<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="https://randomuser.me/api/portraits/thumb/women/67.jpg">
<h3>iboya vat</h3>
<span class="email">iboya.vat#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 07/15/15</span>
</div>
</li>
</ul>
There's no error in the html, it just continues down with more and more li's, and then closes up with a ul and a closing div tag. Then the script app js appears later.
I'm getting an Uncaught TypeError: Cannot set property 'display' of undefined Array.forEach
Basically, it's not recognizing each item in the list in the for each loop. Why is that? When I console log the items, the HTML collection shows up.

Javascript - image button change on click

This is my code, which I got from this site, which is confirmed as working. Not for me. Don't mind the div tag.
Paths are good, it's showing images in DW, but nothing happens after clicking on image on website...
Also, heres the code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- Behavioral Meta Data -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<!-- Styles -->
<link rel="stylesheet" type="text/css" href="Style.css"/>
<title>Untitled Document</title>
</head>
<body>
<div id="container" class="container">
<ul id="scene" class="scene border fill">
<li id="Par_3" class="layer expand-width" data-depth="0.25"><img src="../Img/Par_3.svg" alt="Gallery"></li>
<li id="Par_2" class="layer expand-width" data-depth="0.20"><img src="../Img/Par_2.svg" alt="Grass_1"></li>
<li id="Par_25" class="layer expand-width" data-depth="0.20"><img src="../Img/Par_2.5.svg" alt="About me"></li>
<li id="Par_1" class="layer expand-width" data-depth="0.15"><img src="../Img/Par_1.svg" alt="Grass_2"></li>
<li id="Par_15" class="layer expand-width" data-depth="0.15"><img src="../Img/Par_1.5.svg" alt="Contact"></li>
<li id="Par_0" class="layer expand-width" data-depth="0.10"><img src="../Img/Par_0.svg" alt="Rock"></li>
<li id="Logo" class="layer expand-width" data-depth="0.05"><img src="../Img/Logo.svg" alt="Logo"></li>
</ul>
<img alt="" src="../Img/Click_u.svg" id="cm" onclick="changeImage()" />
</div>
<!-- Scripts -->
<script language="javascript">
function changeImage() {
if (document.getElementById("cm").src == "../Img/Click_u.svg")
{
document.getElementById("cm").src = "../Img/Click_ch.svg";
}
else
{
document.getElementById("cm").src = "../Img/Click_u.svg";
}
}
</script>
<script src="Parallax.js"></script>
<script>
var scene = document.getElementById('scene');
var parallax = new Parallax(scene);
</script>
</body>
</html>
The thing is, .src returns not only the relative path (../Img/Click_u.svg) but the entire path (http://www.yourwebsite.com/images/Img/Click_u.svg).
So that if condition will never be true, and it will never change the image.
Perhaps try something along the lines of
if (document.getElementById("cm").src.indexOf("Click_u.svg") != -1)
To check if the snippet "Click_u.svg" can be found inside the larger string src.
Or use
document.getElementById("cm").getAttribute("src")`
and it will return you the exact value of the attribute (which is the relative path)
The code that should work on your case:
if (document.getElementById("cm").getAttribute("src") == "../Img/Click_u.svg")
{
document.getElementById("cm").src = "../Img/Click_ch.svg";
}
else
{
document.getElementById("cm").src = "../Img/Click_u.svg";
}
For some weird reason, there seems to be an invisible character just at the end of the getAttribute method. No clue as to why, but if you, reader, are willing to use this code, please retype it instead of copy-pasting.
That's a bug for another time

how to load an external html file that contains scripts

Unfortunately, I am not sure to understand anything to java, jquery and all this kind of thing. Nevertheless, I am trying to get some inspiration on forums in order to make a personal website that contains a vertical navbar and a div container in which external html pages will be loaded. Each html file uses an html5 applet called JSmol, which plots 3D molecules that can be manipulated interactively. The main page looks like this:
<!DOCTYPE html>
<html>
<head>
<title> 3D Chemistry </title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" type="text/css" href="Chem3D-CSS/MolChem.css" />
<link href='http://fonts.googleapis.com/css?family=Archivo+Narrow' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<!-- META TAGS start -->
<meta name="Title" content="Molecular Chemistry" />
<meta charset="UTF-8">
<!-- META TAGS end -->
<script type="text/javascript">
$(document).ready(function() {
// select all the links with class="lnk", when one of them is clicked, get its "href" value
// load the content from that URL and check the "status" of the request
// place the response or an error message into the tag with id="content"
$('a.lnk').click(function() {
var url = $(this).attr('href');
$('#content').load(url, function(response, status, xhr) {
// check the status, if "success", place the response into #content
// else, if "error", define an error message and insert it into #content
// else, display an Alert with the status
if(status=='success') {
$('#content').html(response);
}
else if(status=='error') {
var ermsg = '<i>There was an error: '+ xhr.status+ ' '+ xhr.statusText+ '</i>';
$('#content').html(ermsg);
}
else { alert(status); }
});
return false;
})
});
</script>
</head>
<body class="s_page" alink="#ee0000" link="#0000ee" vlink="#551a8b">
<div id="header"> <a id="UPS-link" href="http://www.univ-tlse3.fr/" title="Paul Sabatier University - Toulouse III">
<img src="Chem3D-IMAGES/UT3_PRES_logoQ.png" alt="Paul Sabatier University" id="logoUPS" width=300px />
</a>
</div>
<div id="vmenu">
<ul>
<li>Home</li>
<li>3D Molecules
<ul>
<li>Mol1</li>
<li>Mol2</li>
</ul>
</li>
<li>Symmetry
<ul>
<li>Symmetry Elements
<ul>
<li>C<sub>2</sub>H<sub>6</sub></li>
<li>Ru<sub>4</sub>H<sub>4</sub>(CO)<sub>12</sub></li>
</ul>
</li>
<li>Point Groups
</li>
</ul>
</li>
<li>Solids
<ul>
<li>fcc</li>
<li>hcp</li>
</ul>
</li>
</ul>
</div>
<div id="content">
</div>
<div class="s_author" id="footer">
author: romuald.poteau_at_univ-tlse3.fr
<br/>last modification: 2013/12/16
</div>
</body>
</html>
Up to now, I have worked on the PG.html file (Point Group entry in the vertical menu), which works perfectly fine when it is loaded separately. But is not the case when it is loaded inside the main page as an external html page. The title is the only thing that appears, it seems that the jsmol application is not properly initialized. May be this is specific to the invocation of jsmol ; or is this a general issue when one wants to load hmtl files with embedded scripts ?
<!DOCTYPE html>
<html>
<head>
<title> POINT GROUPS </title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" type="text/css" href="Chem3D-CSS/MolChem.css" />
<!-- META TAGS start -->
<meta name="Title" content="Molecular Chemistry" />
<meta name="Format" content="text/html" />
<meta name="Language" content="en" />
<meta charset="UTF-8">
<!-- META TAGS end -->
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="./JSmol.min.js"></script>
<script type="text/javascript">
// ---------------------------------------------------------------------------------
////// every page will need one variable and one Info object for each applet object
var Info = {
width: 500,
height: 500,
color: "0xC0C0C0",
use: "HTML5",
jarPath: "java",
j2sPath: "j2s",
jarFile: "JmolApplet.jar",
isSigned: false,
addSelectionOptions: false,
serverURL: "php/jsmol.php",
readyFunction: jmol_isReady,
console: "jmol_infodiv",
disableInitialConsole: true,
debug: false,
}
</script>
</head>
<body class="s_page" alink="#ee0000" link="#0000ee" vlink="#551a8b">
<div class="s_title" id="titlePG">
Point Groups
</div>
<div class="s_normal" id="mainPG">
<table border="0">
<tbody>
<tr valign="top">
<td nowrap="nowrap">
<script type="text/javascript">
Jmol.getApplet("Jmol1", Info);
Jmol.script(Jmol1,'load Chem3D-data/nh2cl.xyz;');
Jmol.resizeApplet(Jmol1, 500);
</script>
<br>
</td>
<td>
<script>
Jmol.setButtonCss(null,"style='width:300px'")
Jmol.jmolButton(Jmol1,"load Chem3D-data/nh2cl.xyz;", "NH2Cl (Cs)");
Jmol.jmolBr();
Jmol.jmolButton(Jmol1,"load Chem3D-data/cis-dichloroethylene.xyz;", "cis-dichloroethylene (C2v)");
Jmol.jmolBr();
Jmol.jmolButton(Jmol1,"load Chem3D-data/trans-dichloroethylene.xyz;", "trans-dichloroethylene (C2h)");
</script>
<br>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
I have tried to find an answer to this question by checking previous posts, but my poor skills do not allow me to identify relevant suggestions for such issue.
Thanks for any help.
// Create a DOM object from a URL
$html = file_get_html('http://www.google.com/');
// Create a DOM object from a HTML file
$html = file_get_html('test.htm');

Categories

Resources