jQuery load executes but callback is not executed - javascript

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.

Related

Fetching image/title in an API wth 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.

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

function that calls the next element in a ul

Trying to understand how Javascript and HTML5 work. I have a nav and when you press Part One I'm trying to show Content 1, when you press Part Two..etc. I have tried a couple things, and I am clearly not understand the .next properly, but I can only get it to show the first element, but when I press Part Two, Content Two doesn't show. I guess I am visualizing it wrong, instead of .first(), .next made sense to me since I feel like that would just get the next element. Anyways, here's some code, thanks in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 6 | jQuery Usability </title>
<link rel="stylesheet" href="stylesheet.css">
<!-- This matches the CSS width to the device width, and prevents forced overview without disabling zooming -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Helpful for older Blackberries -->
<meta name="HandheldFriendly" content="True">
<!-- Helpful for older IE mobile -->
<meta name="MobileOptimized" content="320">
<!-- Apple iOS-specific -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<!-- enforce CSS3 media queries in IE 8 and older -->
<!--[if lt IE 9]>
<script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script>
<![endif]-->
<!-- Note: this won't work when testing locally; you'll need to upload your files to a server to test it in IE -->
<!-- HTML5shiv, for IE 6, 7 and 8 -->
<!--[if lte IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script>
<![endif]-->
<!-- jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('ul').hide();
$('a.btnDown').click(function() {
$('nav>ul').fadeIn(200);
}); //closes a.btnDown
$('a.contentDown').click(function() {
$('body>aside>ul').first().fadeIn(200);
}); //closes contentDown
}); //closes .ready()
</script>
</head>
<body>
<nav>
<h1><a class="btnDown" href="#"> Main Menu </a></h1>
<ul>
<li><a class="contentDown" href="#"> Part One </a></li>
<li><a class="contentDown" href="#"> Part Two </a></li>
<li><a class="contentDown" href="#"> Part Three </a></li>
<li><a class="contentDown" href="#"> Student Notes 1 </a></li>
<li><a class="contentDown" href="#"> Student Notes 2 </a></li>
<li><a class="contentDown" href="#"> Student Notes 3</a></li>
</ul>
</nav>
<aside>
<ul>
<li> Content 1 </li>
</ul>
<ul>
<li> Content 2 </li>
</ul>
<ul>
<li> Content 3 </li>
</ul>
<ul>
<li> Content 4 </li>
</ul>
<ul>
<li> Content 5 </li>
</ul>
<ul>
<li> Content 6 </li>
</ul>
</aside>
<figure>
<!-- PUT TV IMAGE HERE -->
</figure>
</body>
</html>
With the given markup, the easiest solution is to work with the index of the elements as shown below
$(document).ready(function () {
$('ul').hide();
$('a.btnDown').click(function () {
$('nav>ul').fadeIn(200);
return false;
}); //closes a.btnDown
//all the content elements
var $suls = $('body>aside>ul');
var $as = $('a.contentDown').click(function () {
//hide visible content item
$suls.filter(':visible').hide();
//display the content item in the same position as the clicked contentDown
$suls.eq($as.index(this)).fadeIn(200);
}); //closes contentDown
}); //closes .ready()
Demo: Fiddle
You can use:
$('ul').hide();
$('a.btnDown').click(function () {
$('nav>ul').fadeIn(200);
});
$('a.contentDown').click(function () {
var idx = $(this).index('.contentDown');
$('body>aside>ul:eq(' + idx + ')').fadeIn(200).siblings('ul').hide();
});
Fiddle Demo

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