createElement Unique Identifier - html

I am building a little gallery in Html and I am having some trouble with it. I have a for loop that creates an img every time it iterates. The problem is that once I have all the images produced and I try to pass a unique variable to my other function which displays the clicked image, there are no unique values I can pass.
I'm probably not explaining it well, but if you run it you'll see what I mean. Any help figuring out how I can obtain a unique identifier for each of the thumbnails would be greatly appreciated.
Below is the code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
function loadPictures(){
var a = new Array();
a[0] = '1-m';
a[1] = '2-m';
a[2] = '3-m';
document.getElementById('inWin').innerHTML='<img src="images/1-m.png" width="620px" height="auto" />';
var ci = document.getElementById('pics');
var newImg, divIdName;
for(x=0; x<a.length; x++)
{
newImg = document.createElement('img');
divIdName = 'portrait'+x;
newImg.setAttribute('id',divIdName);
newImg.setAttribute('src', 'images/' + a[x] + 'thumb.png');
newImg.setAttribute('onclick','changeContent(x);'); // for FF
newImg.onclick = function() {changeContent(x);}; // for IE
ci.appendChild(newImg);
}
}
</script>
<script>
function changeContent(num){
alert(num);
var a = new Array();
x=num;
a[0] = '1-m';
a[1] = '2-m';
a[2] = '3-m';
document.getElementById('inWin').innerHTML='<img src="images/'+ a[x] +'thumb.png" width="620px" height="auto" />';
}
</script>
</head>
<body onload="loadPictures()">
<div id="inWin">
</div>
<div id="pics">
</div>
</body>
</html>
Since I am a newer member I can't upload the image, sorry.

Each of the images already has a unique identifier, the ID attribute. You can work with this in different ways to get what you want. here's an idea of what it would look like:
<script>
var a = [ '1-m',
'2-m',
'3m'
];
function loadPictures(){
document.getElementById('inWin').innerHTML='<img src="images/1-m.png" width="620px" height="auto" />';
var ci = document.getElementById('pics');
var newImg, divIdName;
for(x=0; x<a.length; x++)
{
newImg = document.createElement('img');
divIdName = 'portrait'+x;
newImg.setAttribute('id',divIdName);
newImg.setAttribute('src', 'images/' + a[x] + 'thumb.png');
if(document.addEventListener)
newImg.addEventListener('click', changeContent, false);
else if(document.attachEvent)
newImg.attachEvent('onclick', changeContent);
ci.appendChild(newImg);
}
}
function changeContent(){
x = this.id.split('portrait')[1];
document.getElementById('inWin').innerHTML='<img src="images/'+ a[x] +'.png" width="620px" height="auto" />';
}
</script>

Related

Get data from database and append data to aframe

I want to get data from database and append that data to aframe. I did and data is getting from the database but not appending to the aframe scene. Here is my working flow.
This index file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<a-scene id="scene">
<a-camera id="camera" position="0 0 2" >
</a-camera>
<a-sky color="#000"></a-sky>
</a-scene>
<script>
var ajax = new XMLHttpRequest();
var method = "GET";
var url = "data.php";
var asychronous = true;
ajax.open(method,url,asychronous);
ajax.send();
ajax.onreadystatechange = function(){
if(this.readyState==4 && this.status==200){
var data = JSON.parse(this.responseText);
console.log(data);
var html = "";
var username = "";
for(var i=0;i<data.length;i++){
username = data[i].username;
html += "<a-scene>";
html += +username;
html += "</a-scene>";
}
var totalText1 = document.createElement('a-text');
totalText1.setAttribute('position',{x:0, y:0, z:0});
totalText1.setAttribute('color',"#fff");
totalText1.setAttribute('value',username);
totalText1.setAttribute('scale',{x:1.6, y:1.6, z:1.6});
document.getElementById("scene").appendChild(totalText1);
}
}
</script>
</body>
</html>
Here is data.php file
<?php
$conn = mysqli_connect("localhost","root","","test");
$query = "SELECT * FROM usertest WHERE language='english'";
$result = mysqli_query($conn,$query);
$data = array();
while($row = mysqli_fetch_assoc($result)){
$data = $row;
}
echo json_encode($data);
?>
Data retrieving is okay.But is there any way to append those data to aframe scene?
Double check the entity is actually getting appended to the scene. It looks right. Check the Inspector (ctrl/alt/i) or DOM Inspector or query selector from console. The 0/0/0 position might just make it hard to see.

Transferring HTML data between pages

Been really stressed out for a while, as I'm very new to coding and can't figure out how to transfer some paragraph data across pages.
Here is my code on my first page:
<!DOCTYPE>
<html>
<head>
<h1>z</h1>
</head>
<body>
<p>test</p>
<p id="goalPage"></p>
<script type="text/javascript">
var t = Math.floor((Math.random() * 1) + 1);
if (t === 1) {document.getElementById("goalPage").innerHTML = "Your goal page is Data 1";}
else {alert('Unprecedented failure. Please reload the page and report the bug to me.');}
function testJS() {
var b = document.getElementById('goalPage').value,
url = 'file:///C:/Users/Admin/Desktop/Coding%20Data%20Files/data1.html?name=load' + encodeURIComponent(b);
document.location.href = url;
}
</script>
On my second page, this is my code:
<!DOCTYPE>
<html>
<head>
<h1>w</h1>
</head>
<body>
<p id="goalPage"></p>
<script>
window.onload = function () {
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('goalPage').innerHTML = data.load;
}
</script>
</body>
</html>
I used many other forum answers to try to get a working solution, however I could not. Any help would be appreciated.

Syncing the playing of audio files

I wish to play a list of words. Each word is represented by audio recordings of that word in three different dialects. All three audio files should start playing simultaneously, for each word. The code below works most of the time, but sometimes the three audio files will play out of sync for a given word. Why is this and how can I fix it?
UPDATE:
I think the issue is that the audio has to be fetched and stored on the client's machine in some sort of cache. This is my conclusion at least since I notice that problems are more prevalent when new words are added to the playlist. Can I cache all the audio for all words before I start playing?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Player</title>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
var _dialects = ["c","m","u"];
var _playlist =
[
"ta_x",
"me_x",
"ag",
"rith",
"agus",
"ag",
"ceol",
];
var _players = new Array();
for (var i=0;i<_dialects.length;i++)
{
_players[i] = document.getElementById("audio_player_"+(i+1));
}
var _number_of_available_players = _dialects.length;
var _playlist_index = 0;
var _play_button = document.getElementById("play_button");
function play()
{
_playlist_index = 0;
_play_button.disabled = true;
next();
}
function next()
{
if(_number_of_available_players == _dialects.length)
{
if(_playlist_index < _playlist.length)
{
for (var i=0;i<_players.length;i++)
{
if (_players[i].canPlayType('audio/mpeg;'))
{
_players[i].src = "http://www.focloir.ie/media/ei/sounds/" + _playlist[_playlist_index] + "_"+_dialects[i]+".mp3";
}
else
{
_players[i].src = "http://www.focloir.ie/media/ei/sounds_ogg/" + _playlist[_playlist_index] + "_"+_dialects[i]+".ogg";
}
_players[i].play();
}
_playlist_index = _playlist_index + 1;
_number_of_available_players = 0;
}
else
{
_play_button.disabled = false;
}
}
}
function end()
{
_number_of_available_players = _number_of_available_players + 1
next();
}
for (var i=0;i<_players.length;i++)
{
_players[i].addEventListener('ended', end);
}
_play_button.addEventListener('click', play);
}//]]>
</script>
</head>
<body>
<audio id = "audio_player_1"></audio>
<audio id = "audio_player_2"></audio>
<audio id = "audio_player_3"></audio>
<button id = "play_button">Play</button>
</body>
</html>

How to put the data taken from google custom search API to checkbox list

I have a code which takes data from google custom search API, There is no wrong with the custom search API part, it retrieves data without any error
<html>
<head>
<title>JSON Custom Search API Example</title>
</head>
<body>
<div id="content"></div>
<script>
var pageName = new Array();
var pageLink = new Array();
var pageDetails = new Array();
function hndlr(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
pageName[i] = item.title;
pageLink[i] = item.link;
pageDetails[i] = item.htmlSnippet;
}
}
// Some codes
var search_query = 'https://www.googleapis.com/customsearch/v1?key=MY_KEY&cx=XXXXXXXXX&q='+query+'&start=1&callback=hndlr';
s = document.createElement('script');
s.src = search_query;
document.getElementsByTagName('head')[0].appendChild(s);
</script>
</body>
</html>
Required data are saved in the pageName, pageLink and pageDetails arrays.
Now I want display them with chechboxes and allow user to select them.
I need to take the links of the selected sites(pageLink variable) and pass it to anothe file using POST method
I tried using bellow code just before end of the body tag()
<form action="b.php" method="post">
<script>
for (var j = 0; j < 5; j++) {
document.write("<input type='checkbox' name='formDoor[]' id='"+j+"' value= '' />"+pageName[j]+"<br />");
document.getElementById(j).value = pageLink[j];
}
</script>
<input type="submit" name="formSubmit" value="Submit" />
</form>
But in the other file, it says variables are undefined. seems like variables doesn't pass to the 'b.php' file
Can anyone please tell me how to do this?
Your current code for adding checkboxes would likely be executed before the search result arrives (i.e.: before hndlr is executed), so all arrays are still empty. The solution would be to move the checkbox creation code into the hndlr function.
Here's the fixed page.
<html>
<head>
<title>JSON Custom Search API Example</title>
</head>
<body>
<div id="content"></div>
<form id="bform" action="b.php" method="post">
<input type="submit" name="formSubmit" value="Submit" />
</form>
<script>
var pageName = new Array();
var pageLink = new Array();
var pageDetails = new Array();
function hndlr(response) {
var f=document.getElementById('bform'), prev=f.children[0];
for (var i = 0; i < response.items.length; i++) {
var ele, item = response.items[i];
pageName[i] = item.title;
pageLink[i] = item.link;
pageDetails[i] = item.htmlSnippet;
ele = document.createElement('BR');
f.insertBefore(ele, prev);
prev = ele;
ele = document.createTextNode(pageName[i]);
f.insertBefore(ele, prev);
prev = ele;
ele = document.createElement('INPUT');
ele.type = 'checkbox';
ele.name = 'formDoor[]';
ele.id = i;
ele.value = encodeURI(pageLink[i]);
f.insertBefore(ele, prev);
prev = ele;
}
}
// Some codes
var search_query = 'https://www.googleapis.com/customsearch/v1?key=MY_KEY&cx=XXXXXXXXX&q='+query+'&start=1&callback=hndlr';
s = document.createElement('script');
s.src = search_query;
document.getElementsByTagName('head')[0].appendChild(s);
</script>
</body>
</html>

How to get info from background_page to popup?

I'm following the official Chrome Extension tutorial called Chritter where they fetch tweets from Twitter and place them into the extension. I'm trying to do similar except im trying to fetch items from an xml file.
My XML
<xml>
<item>
<title>Title 1</title>
<description>Description 1</description>
<duration>55:00</duration>
<published>28/01/2011</published>
</item>
<item>
<title>Title 2</title>
<description>Description 2</description>
<duration>55:00</duration>
<published>28/01/2011</published>
</item>
</xml>
background.html
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var fetchFreq = 30000; // how often we fetch new items (30s)
var req; // request object
var unreadCount = 0; // how many unread items we have
var items; // all currently fetched items
getItems();
//setInterval(getItems, fetchFreq);
function getItems(){
req = new XMLHttpRequest();
req.open("GET", "http://urltoxml.com/xmlfile.xml", false);
req.onload = processItems;
req.send();
}
function processItems(){
xmlDoc = req.responseXML;
items = xmlDoc.getElementsByTagName("item");
unreadCount += items.length;
if (unreadCount > 0) {
chrome.browserAction.setBadgeBackgroundColor({
color: [255, 0, 0, 255]
});
chrome.browserAction.setBadgeText({text: '' + unreadCount});
}
items = xmlDoc.concat(items);
}
</script>
</head>
</html>
I don't know how to get the fetched items from the background.html and displayed onto the popup.html ?
popup.html
<html>
<head>
<link rel="stylesheet" href="popup.css" />
<script src="util.js"></script>
<script>
var bg; // background page
// timeline attributes
var timeline;
var template;
var title;
var link;
var description;
onload = setTimeout(init, 0); // workaround for http://crbug.com/24467
// initialize timeline template
function init() {
chrome.browserAction.setBadgeText({text: ''});
bg = chrome.extension.getBackgroundPage();
bg.unreadCount = 0;
timeline = document.getElementById('timeline');
template = xpath('//ol[#id="template"]/li', document);
title = xpath('//div[#class="text"]/span', title);
content = xpath('//div[#class="text"]/span', template);
update();
}
function update(){
// how to do this ?
// See Chritter example below with JSON,
// except i want to it with xml ?
}
</script>
</head>
<body>
<div id="body">
<ol id="timeline" />
</div>
<ol id="template">
<li>
<div class="text">
<a></a>
<span></span>
</div>
<div class="clear"></div>
</li>
</ol>
</body>
</html>
The way the Chritter extension does it only seems to work with JSON. Here is how they do it:
// update display
function update() {
var user;
var url;
var item;
for (var i in bg.tweets) {
user = bg.tweets[i].user;
url = 'http://twitter.com/' + user.screen_name;
// thumbnail
link.title = user.name;
link.href = openInNewTab(url);
image.src = user.profile_image_url;
image.alt = user.name;
// text
author.href = openInNewTab(url);
author.innerHTML = user.name;
content.innerHTML = linkify(bg.tweets[i].text);
// copy node and update
item = template.cloneNode(true);
timeline.appendChild(item);
}
}
Chritter background.html
<html>
<head>
<script type="text/javascript">
var fetchFreq = 30000; // how often we fetch new tweets (30s)
var req; // request object
var unreadCount = 0; // how many unread tweets we have
var tweets; // all currently fetched tweets
getTweets();
setInterval(getTweets, fetchFreq);
// fetch timeline from server
function getTweets() {
req = new XMLHttpRequest();
req.open('GET', 'http://twitter.com/statuses/public_timeline.json');
req.onload = processTweets;
req.send();
}
// process new batch of tweets
function processTweets() {
var res = JSON.parse(req.responseText);
unreadCount += res.length;
if (unreadCount > 0) {
chrome.browserAction.setBadgeBackgroundColor({
color: [255, 0, 0, 255]
});
chrome.browserAction.setBadgeText({text: '' + unreadCount});
}
tweets = res.concat(tweets);
}
</script>
</head>
</html>
Any help much appreciated! Thanks!
If you want to access items var from a background page then:
var items = chrome.extension.getBackgroundPage().items;
I am not sure what the exact question is, but the general practice is to store the data from background page into localstorage and then access this data from the popup page.
http://www.rajdeepd.com/articles/chrome/localstrg/LocalStorageSample.htm