I have been playing with this code for a while and I was wondering why when I try to add img’s to the array on the js code makes the images appear on DOM but also makes a bunch of Undefined elements appear, How can I just make the 15 images appear without the undefined? Thanks
enter link description here
var previous = document.getElementById('btnPrevious')
var next = document.getElementById('btnNext')
var gallery = document.getElementById('image-gallery')
var pageIndicator = document.getElementById('page')
var galleryDots = document.getElementById('gallery-dots');
var images = ["https://exoplanets.nasa.gov/internal_resources/1763/",
"https://cdn.britannica.com/56/234056-050-0AC049D7/first-image-from-James-Webb-Space-Telescope-deepest-and-sharpest-infrared-image-of-distant-universe-to-date-SMACS-0723.jpg",
"https://assets.newatlas.com/dims4/default/ac389ce/2147483647/strip/true/crop/1620x1080+150+0/resize/1200x800!/quality/90/?url=http%3A%2F%2Fnewatlas-brightspot.s3.amazonaws.com%2Farchive%2Funiverse-expanding-acceleration-1.jpg",
"https://media.newyorker.com/photos/590966ee1c7a8e33fb38d6cc/master/w_2560%2Cc_limit/Nissan-Universe-Shouts.jpg",
"https://www.thoughtco.com/thmb/NY5k_3slMRttvtS7mA0SXm2WW9Q=/1500x0/filters:no_upscale():max_bytes(150000):strip_icc()/smallerAndromeda-56a8ccf15f9b58b7d0f544fa.jpg",
"https://static.scientificamerican.com/sciam/cache/file/05B8482C-0C04-4E41-859DCCED721883D2_source.jpg?w=590&h=800&7ADE2895-F6E3-4DF4-A11F51B652E9FA88",
"https://qph.cf2.quoracdn.net/main-thumb-66277237-200-huqebnzwetdsnnwvysbxemlskpcxnygf.jpeg",
"http://www.pioneertv.com/media/1090/hero_shot_1080x720.jpg?anchor=center&mode=crop&width=600&height=400&rnd=133159257140000000",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRSWFW1EpMNFM5-dbZEUUnzJkzT3KbUCeuhPHx_eseFCpPeX4Q_DIVPopjS0LeKVmKdQho&usqp=CAU",
"https://cdn.mos.cms.futurecdn.net/rwow8CCG3C3GrqHGiK8qcJ.jpg",
"https://static.wixstatic.com/media/917d103965314e2eacefed92edb6492c.jpg/v1/fill/w_640,h_356,al_c,q_80,usm_0.66_1.00_0.01,enc_auto/917d103965314e2eacefed92edb6492c.jpg",
"https://astronomy.com/~/media/A5B9B6CF36484AB9A6FFAE136C55B355.jpg",
"https://discovery.sndimg.com/content/dam/images/discovery/fullset/2022/9/alien%20planet%20GettyImages-913058614.jpg.rend.hgtvcom.616.411.suffix/1664497398007.jpeg",
"https://images.newscientist.com/wp-content/uploads/2017/06/21180000/planet-10-orange-blue-final-small.jpg?crop=16:9,smart&width=1200&height=675&upscale=true",
"https://images.hindustantimes.com/img/2022/07/20/1600x900/Viral_Instagram_Planet_Rainbow_Nasa_1658316556293_1658316573815_1658316573815.PNG"
]
for (var i = 0; i < 15; i++) {
images.push({
title: "Image " + (i + 1),
source: images[i]
});
}
var perPage = 8;
var page = 1;
var pages = Math.ceil(images.length / perPage)
// Gallery dots
for (var i = 0; i < pages; i++){
var dot = document.createElement('button')
var dotSpan = document.createElement('span')
var dotNumber = document.createTextNode(i + 1)
dot.classList.add('gallery-dot');
dot.setAttribute('data-index', i);
dotSpan.classList.add('sr-only');
dotSpan.appendChild(dotNumber);
dot.appendChild(dotSpan)
dot.addEventListener('click', function(e) {
var self = e.target
goToPage(self.getAttribute('data-index'))
})
galleryDots.appendChild(dot)
}
// Previous Button
previous.addEventListener('click', function() {
if (page === 1) {
page = 1;
} else {
page--;
showImages();
}
})
// Next Button
next.addEventListener('click', function() {
if (page < pages) {
page++;
showImages();
}
})
// Jump to page
function goToPage(index) {
index = parseInt(index);
page = index + 1;
showImages();
}
// Load images
function showImages() {
while(gallery.firstChild) gallery.removeChild(gallery.firstChild)
var offset = (page - 1) * perPage;
var dots = document.querySelectorAll('.gallery-dot');
for (var i = 0; i < dots.length; i++){
dots[i].classList.remove('active');
}
dots[page - 1].classList.add('active');
for (var i = offset; i < offset + perPage; i++) {
if ( images[i] ) {
var template = document.createElement('div');
var title = document.createElement('p');
var titleText = document.createTextNode(images[i].title);
var img = document.createElement('img');
template.classList.add('template')
img.setAttribute("src", images[i].source);
img.setAttribute('alt', images[i].title);
title.appendChild(titleText);
template.appendChild(img);
template.appendChild(title);
gallery.appendChild(template);
}
}
// Animate images
var galleryItems = document.querySelectorAll('.template')
for (var i = 0; i < galleryItems.length; i++) {
var onAnimateItemIn = animateItemIn(i);
setTimeout(onAnimateItemIn, i * 100);
}
function animateItemIn(i) {
var item = galleryItems[i];
return function() {
item.classList.add('animate');
}
}
// Update page indicator
pageIndicator.textContent = "Page " + page + " of " + pages;
}
showImages();
I checked your code and make it work with a small modification.
You are reusing the same array with the links of images and push inside the new object with the shape of { title, source }.
You just need to do this changes:
Change the name of your array of images. Something from images to arrayOfImages.
const arrayOfImages = ["https://exoplanets.nasa.gov/internal_resources/1763/", ...]
Declare an empty array before your first for loop. Make something like const images = []
On your for loop, instead of loop over the images variable, do it over the arrayOfImages variable.
const images = [];
for (var i = 0; i < 15; i++) {
images.push({
title: "Image " + (i + 1),
source: arrayOfImages[i]
});
}
With those changes, everything works for me.
Also, as a recommendation, try to avoid the var keyword. If you want more details about this, this answer is very helpful: https://stackoverflow.com/a/50335579/17101307
You can use Array#map to create a new array of objects from the array of URLS, then replace the original array.
images = images.map((x, i) => ({
title: "Image " + (i + 1),
source: x
}));
Related
Is it possible to compare filenames for a set of files that are imported as Photoshop layers ?
I have a folder of 50 jpg images which I have used in a PSD file.
Now I want to check whether all the JPG files are used or not ?
Is it possible to do so ?
As I've said, Photoshop scripting can help you achieve this by using File Objects and basic javascript knowledge. I've modified my old script as you've desired and now it should work well with any nested groups and images.
I highly encourage you to learn scripting and ask questions here wherever you feels confused.
Save below code as 'Script.jsx' and run it from 'File > Scripts > Browse'
Update 2 : Now it saves log.txt file too as per you requested. P.S. Learn from this script and tweak it to your desired result.
// Managing Document
var docs = app.documents;
// Progress Bar
var win = new Window("window{text:'Progress',bounds:[100,100,400,150],bar:Progressbar{bounds:[20,20,280,31] , value:0,maxvalue:100}};");
// assigning activeDocument
if (docs.length != 0) {
var docRef = app.activeDocument;
// Defining the folder
alert("You will be prompted for the folder containing your images.\n" +
"Files will be selected with a '.png'/'.jpg/.jpeg' on the end in the same folder.");
var folder = Folder.selectDialog();
if (!folder) {
exit;
}
var photoFiles = folder.getFiles(/\.(jpg|jpeg|png)$/i);
var matchFiles = [];
var photoFilesName = [];
//Searching for used images
var increment = parseFloat(0);
var divider = parseFloat(100/photoFiles.length);
win.show();
for (var i = 0; i < photoFiles.length; i++) {
increment = increment + divider;
var indexPhotoName = removeExtension(photoFiles[i].displayName);
photoFilesName.push(indexPhotoName);
var doc = activeDocument;
var curLayer;
goThroughLayers(doc, indexPhotoName);
}
function goThroughLayers(parentLayer, targetName) {
for (var i = 0; i < parentLayer.layers.length; i++) {
curLayer = parentLayer.layers[i];
doc.activeLayer = curLayer;
if (curLayer.typename == 'LayerSet') {
goThroughLayers(curLayer, targetName)
} else {
if (curLayer.name == targetName) {
// if (curLayer.name.match(/[e]/ig)) {
matchFiles.push(targetName);
// }
} //end if
} //end else
} //end loop
} //end function
function arr_diff(a1, a2) {
var a = [],
diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
}
function removeExtension(str) {
return str.split('.').slice(0, -1).join('.');
}
var missItems = arr_diff(matchFiles, photoFilesName);
if (missItems.length > 0) {
var missFolder = new Folder(photoFiles[0].path + '/Missed%20Files');
if(!missFolder.exists){
missFolder.create();
}
for (var y = 0; y < photoFiles.length; y++) {
var photoTrimName = removeExtension(photoFiles[y].displayName);
for( var x = 0; x < missItems.length ; x++){
if(photoTrimName == missItems[x]){
photoFiles[y].copy(new File(missFolder+'/'+photoFiles[y].displayName));
}
}
};
win.close();
alert("You've missed total " + missItems.length + " files. Press OK to open folder containing missing files. Log report is generated wherever PSD is saved.");
var FileStr = "";
for(var m=0; m<missItems.length; m++){
FileStr = FileStr + '\n' + (m+1) + '. ' + missItems[m];
}
var str = "Your missed files are : " + FileStr;
saveTxt(str);
missFolder.execute();
} else {
win.close();
saveTxt('All Photos are used');
alert('All Photos are used');
}
} else {
alert('Open atleast one document');
}
function saveTxt(txt)
{
var Name = "LogReport_" + app.activeDocument.name.replace(/\.[^\.]+$/, '');
var Ext = decodeURI(app.activeDocument.name).replace(/^.*\./,'');
if (Ext.toLowerCase() != 'psd')
return;
var Path = app.activeDocument.path;
var saveFile = File(Path + "/" + Name +".txt");
if(saveFile.exists)
saveFile.remove();
saveFile.encoding = "UTF8";
saveFile.open("e", "TEXT", "????");
saveFile.writeln(txt);
saveFile.close();
}
In Javascript, it is possible to get some information related to PSD file layers using PSD.js library
In my Chrome extension, I'm trying to scrape information from the current tab (in content.js) and send it as parameter to the provided URL (background.js). It seems like I can scrape everything from the tab and append it to the URL except the values of input tags. Here's my code:
content.js:
var elements = new Array("form","h1","input","td","textarea","time","title","var");
//declare an array for found elements
var foundElements = new Array();
//declare an array for found ids
var foundIds = new Array();
//this counter is used to hold positions in the element array.
var elementCounter = 0;
//this counter is used to hold positions in the foundIds array
var idsCounter = 0;
//this counter is used to hold positions in the classCounter array.
var classCounter = 0;
//and we're going to output everything in a giantic string.
var output = "URL=" + document.URL;
//scrape the page for all elements
for (var i = 0; i < elements.length; i++)
{
var current = document.getElementsByTagName(elements[i]);
if(current.length>0)
{
for (var z=0; z<current.length; z++)
{
var inTxt = current[z].innerText;
output += "&" + elements[i] + "=" + inTxt;
}
elementCounter++;
//now that we have an array of a tag, check it for IDs and classes.
for (var y = 0; y<current.length; y++)
{
//check to see if the element has an id
if(current[y].id)
{
//these should be unique
var hit = false;
for (var x = 0; x<foundIds.length; x++)
{
if(foundIds[x]==current[y].id)
{
hit=true;
}
}
//if there was no hit...
if(!hit)
{
foundIds[idsCounter]=current[y].id;
idsCounter++;
var currVal = current[y].value;
output+="&" + current[y].id + "=" + currVal;
}
}
//now we pull the classes
var classes = current[y].classList;
if(classes.length>0)
{
for (var x = 0; x<classes.Length; x++)
{
var hit = false;
for (var z = 0; z<foundClasses.length; z++)
{
if(foundClasses[z]==classes[x])
{
hit=true;
}
}
//if there was not a hit
if(!hit)
{
foundClasses[classCounter]=classes[x];
classCounter++;
output+="&" + classes[x] + "=";
}
}
}
}
}
}
chrome.runtime.sendMessage({data: output});
background.js:
var output2;
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
output2 = "text_input1=";
output2 += request.data;
});
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.create({url: "http://www.google.com?" + output2}, function(tab) {
chrome.tabs.executeScript(tab.id, {file: "content.js"}, function() {
sendMessage();
});
});
});
Does anyone know why the input tags values are passed as blank?
Because you're trying to get the input text by using current[z].innerText.
However, you have to use current[z].value for inputs.
This uses Raphaeljs to draw a single chord from an array:
function createChordStruct(key, string, shape) {
var string = string.toUpperCase();
var position = positions[string][key];
var struct = chord_shapes[shape];
return {
name: key + struct.name,
chord: struct.chord,
position: position,
position_text: struct.position_text,
bars: struct.bars
}
}
function createChordElement(chord_struct) {
var chordbox = $('<div>').addClass('chord');
var chordcanvas = $('<div>');
var chordname = $('<div>').addClass('chordname');
chordbox.append(chordcanvas);
chordbox.append(chordname);
chordname.append(chord_struct.name);
var paper = Raphael(chordcanvas[0], 150, 140);
var chord = new ChordBox(paper, 30, 30);
chord.setChord(
chord_struct.chord,
chord_struct.position,
chord_struct.bars,
chord_struct.position_text);
chord.draw();
return chordbox;
}
function createSectionElement(section_struct) {
var section = $('<div>').addClass('section');
var section_title = $('<div>').addClass('title');
var section_desc = $('<div>').addClass('description');
section.append(section_title);
section.append(section_desc);
section_title.append(section_struct.section);
section_desc.append(section_struct.description);
return section;
}
And this takes each chord created from the array and puts them in a new div called "chordscroller":
function c_i() {
var randomholder = 'id_' + (Math.floor(Math.random() * 100005) + 1);
var randomId = 'id_' + (Math.floor(Math.random() * 100005) + 1);
$(function () {
$('#sortable').append($('<li id ="' + randomholder + '" class="chordbox"><span id="i" class="scale">C - I</span><span id="' + randomId + '" class=" even scrollpane chordscroller"></span></li>').sortable( "refresh" ))
});
function c_one() {
var container = $("#" + randomId + "");
var column = null;
var column = _.shuffle(c_1);
for (var i = 0; i < column.length; ++i) {
var section_struct = column[i];
var section = createSectionElement(section_struct);
for (var j = 0; j < section_struct.chords.length; ++j) {
section.append(createChordElement(section_struct.chords[j]));
}
container.append(section);
}
}
$(function() { c_one() });
}
The problem is it draws all the chords at the same time and it takes forever. I've tried every combination of setTimeout and setInterval I could think of but I keep running into errors.
Can anybody tell from this code how to get the chords to be drawn one at a time instead of all at once?
Finally figured it out (using a plugin called doTimeout):
$.doTimeout( 1, function() {
chord.setChord(
chord_struct.chord,
chord_struct.position,
chord_struct.bars,
chord_struct.position_text);
chord.draw();
});
Here is the script I have:
And I'm trying to assign event to each element in an array.
window.onload = sliding;
function sliding() {
document.getElementById('tag1').onmouseover = slideout;
document.getElementById('tag1').onmouseout = slidein;
}
And I tried do using the code below but that didn't work. It would trigger all the function buy it self.
window.onload = sliding;
var tags = new Array('tag1','tag2','tag3','tag4','tag5','tag6','tag7','tag8');// List of headings
var pics = new Array('popout1','popout2','popout3','popout4','popout5','popout6','popout7','popout8');// list of images that slide out
function sliding() {
for (var i = 0; i < tags.length; ++i) {
document.getElementById('tag1').onmouseover = setslideout(tags[i],pics[i]);
document.getElementById('tag1').onmouseout= setslidein(tags[i],pics[i]);
}
}
Here is full code
window.onload = sliding;
var tags = new Array('tag1','tag2','tag3','tag4','tag5','tag6','tag7','tag8');// List of headings
var pics = new Array('popout1','popout2','popout3','popout4','popout5','popout6','popout7','popout8');// list of images that slide out
function sliding() {
/*for (var i = 0; i < tags.length; ++i) {
setslideout(tags[i],pics[i]);
}/*/
document.getElementById('tag1').onmouseover = slideout;
document.getElementById('tag1').onmouseout = slidein;
}/*
function setslideout(tagsid,picsid){
document.getElementById(tagsid).onmouseover = slideout(tagsid,picsid);
}*/
function slideout(){
//alert('over '+ lid);
if(currpos('popout1') < 200){
document.getElementById('popout1').style.left = currpos('popout1') + 10 + "px";
var timer = setTimeout(slideout,10)
}else{
clearTimeout(timer);
}
}
function slidein(){
//alert('over '+ lid);
if(currpos('popout1') > 0){
document.getElementById('popout1').style.left = currpos('popout1') - 20 + "px";
var timer2 = setTimeout(slidein,10)
}else{
clearTimeout(timer2);
}
}
function currpos(element){
return document.getElementById(element).offsetLeft;
}
Here what im trying to to http://signsourceak.com/index2.html (first link in the drop down works )
Here's a version of your code modified to use closures, hopefully this does the trick:
window.onload = sliding;
var tags = new Array('tag1','tag2','tag3','tag4','tag5','tag6','tag7','tag8');// List of headings
var pics = new Array('popout1','popout2','popout3','popout4','popout5','popout6','popout7','popout8');// list of images that slide out
function sliding() {
for (var i = 0; i < tags.length; ++i) {
document.getElementById(tags[i]).onmouseover = (function(j){
return function(){
setslideout(tags[j], pics[j]);
}
})(i);
document.getElementById(tags[i]).onmouseout = (function(j){
return function(){
setslidein(tags[j], pics[j]);
}
})(i);
}
}
I'm running the JavaScript below to place horizontal scrolling text on the banner of my website. It works in one server but not another. I get the following error:
Error: 'this.mqo' is null or not an object
JavaScript:
function start() {
new mq('m1');
/* new mq('m2');
*/
mqRotate(mqr); // must come last
}
window.onload = start;
// Continuous Text Marquee
// permission to use this Javascript on your web page is granted
// provided that all of the code below in this script (including these
// comments) is used without any alteration
function objWidth(obj) {
if (obj.offsetWidth) return obj.offsetWidth;
if (obj.clip) return obj.clip.width;
return 0;
}
var mqr = [];
function mq(id) {
this.mqo = document.getElementById(id);
var wid = objWidth(this.mqo.getElementsByTagName('span')[0]) + 5;
var fulwid = objWidth(this.mqo);
var txt = this.mqo.getElementsByTagName('span')[0].innerHTML;
this.mqo.innerHTML = '';
var heit = this.mqo.style.height;
this.mqo.onmouseout = function () {
mqRotate(mqr);
};
this.mqo.onmouseover = function () {
clearTimeout(mqr[0].TO);
};
this.mqo.ary = [];
var maxw = Math.ceil(fulwid / wid) + 1;
for (var i = 0; i < maxw; i++) {
this.mqo.ary[i] = document.createElement('div');
this.mqo.ary[i].innerHTML = txt;
this.mqo.ary[i].style.position = 'absolute';
this.mqo.ary[i].style.left = (wid * i) + 'px';
this.mqo.ary[i].style.width = wid + 'px';
this.mqo.ary[i].style.height = heit;
this.mqo.appendChild(this.mqo.ary[i]);
}
mqr.push(this.mqo);
}
function mqRotate(mqr) {
if (!mqr) return;
for (var j = mqr.length - 1; j > -1; j--) {
maxa = mqr[j].ary.length;
for (var i = 0; i < maxa; i++) {
var x = mqr[j].ary[i].style;
x.left = (parseInt(x.left, 10) - 1) + 'px';
}
var y = mqr[j].ary[0].style;
if (parseInt(y.left, 10) + parseInt(y.width, 10) < 0) {
var z = mqr[j].ary.shift();
z.style.left = (parseInt(z.style.left) + parseInt(z.style.width) * maxa) + 'px';
mqr[j].ary.push(z);
}
}
mqr[0].TO = setTimeout('mqRotate(mqr)', 10);
}
The reason is most likely that there is no element with the id "m1". Place this line first in the start function to diagnose this:
alert(document.getElementById('m1'));
If it shows "[Object]" (or similar), the element exists and it's some other problem, but if it shows "undefined" it means that there is no such element in the page.