Create randomly generated divs that fill a box jQuery and Javascript - javascript

I have a section on my website that is 100% wide and 450 pixels tall.
My html looks like so...
<section class="interactive-banner">
<figure></figure>
</section>
I want each 'figure' element to be 150 pixels wide and 150 pixels tall, I want to generate the 'figure' html automatically and randomly with jQuery, and to consist of some inner html.
I have the following...
$(function(){
var people = [
{ id: 1 },
{ id: 2 }
];
var figure = $('figure');
w = 1500;
h = 450;
var counter = 0;
var data = people[Math.floor(Math.random()*people.length)];
(function nextFade() {
counter++;
figure.clone().html(data.name).appendTo('.interactive-banner').hide().fadeIn(150, function() {
if(counter < 30) nextFade();
});
})();
});
I want each figure element to fade in 1 after the other, in total I will only have 7 original figures, only these 7 will be randomly cloned until i have 30 iterations in total, I want the figure html to contain the data inside each object in my people array, so each figure is an object so to speak, output as so...
<figure>
<img src="[image src from object inside array]" />
<div class="information">
<h5>[name from object inside of array ]</h5>
<p>[job title from object inside of array ]</p>
</div>
</figure>
only at the minute its being output as so...
<figure style="display: block;">
Chris
</figure>
Ive created an example here, as you see however each figure contains the same information...
http://jsfiddle.net/pGmeE/

http://jsbin.com/isopin/1/edit
Don't populate your section initially and don't clone your figure element with jQ. Rather create a new one at every loop iteration.
<section class="interactive-banner"></section>
jQ:
$(function(){
var people = [
{ id: 1, name: 'Justin', title: 'Head Designer', bio: 'This is Justin\'s Biography.', image: 'justin.jpg' },
{ id: 2, name: 'Chris', title: 'Head Developer', bio: 'This is Chris\' Biography.', image: 'chris.jpg' },
{ id: 3, name: 'Sam', title: 'Developer', bio: 'This is Sam\'s Biography.', image: 'sam.jpg' },
{ id: 4, name: 'Haythem', title: 'Developer', bio: 'This is Haythem\'s Biography.', image: 'haythem.jpg' },
{ id: 5, name: 'Geoff', title: 'Designer', bio: 'This is Geoff\'s Biography.', image: 'geoff.jpg' },
{ id: 6, name: 'Liam', title: 'Designer', bio: 'This is Liam\'s Biography.', image: 'liam.jpg' }
];
w = 1500;
h = 450;
var counter = 0;
(function nextFade() {
counter++;
// Give "random" a chance to get random again
var data = people[Math.floor(Math.random()*people.length)];
// Now create a new Figure element:
var figure = $('<figure />');
figure.html(data.name).appendTo('.interactive-banner').hide().fadeIn(150, function() {
if(counter < 30) nextFade();
});
})();
});

Related

Combine two one dimensional arrays to create a cartesian table

I hope you are good.
I am struggling to create a compatible data type in javascript to display a cartesian like table where we have a vertical and a horizontal header.
Basically I have 3 one dimensional arrays where the first two are the table headers, and the third has the combination of those two by id's (basically the table cells).
let horizontal_header = [
{ id: 1, name: 'h1' },
{ id: 2, name: 'h2' },
];
let vertical_header = [
{ id: 10, name: 'r1' },
{ id: 11, name: 'r2' },
];
let cells = [
{ hid: 1, vid: 10, id: 7, name: 'c1' },
{ hid: 1, vid: 11, id: 8, name: 'c2' },
{ hid: 2, vid: 10, id: 9, name: 'c3' },
{ hid: 2, vid: 11, id: 10, name: 'c4' },
],
Also it can happen that a combination might not exists in that case, I want to enter an empty cell or something obvious that this cell is missing.
I want to create a table like below:
h1
h2
r1
c1
c3
r2
c2
c4
I would appreciate any suggestion and be very thankful to help me solve this complex use-case using Angular for rendering the table template.
Thank you.
I'd approach this problem by parsing the cells into more table-render friendly format like below. Note: I used ### separator, you can use anything that suits for coding practice.
let output = {};
cells.forEach(cell => {
output[cell.hid + '###' + cell.vid] = {
id: cell.id,
name: cell.name,
};
});
After that, you can use the output object to render the table cell as you already know the combination of hid and vid. You can prepare/render your table rows as below.
const rows = [];
for (let i = 0; i < horizontal_header.length; i++) {
const row = [];
for (let j = 0; j < vertical_header.length; j++) {
const hid = horizontal_header[i];
const vid = vertical_header[j];
if (output[hid + '###' + vid]) {
row.push(output[hid + '###' + vid].name);
} else {
row.push('-');
}
}
rows.push(row);
}

Get text of previous header in HTML

I have a HTML which looks like this:
<h1>Title</h1>
<p>Some additional content, can be multiple, various tags</p>
<h2><a id="123"></a>Foo</h2>
<p>Some additional content, can be multiple, various tags</p>
<h3><a id="456"></a>Bar</h3>
Now, for each anchor with id, I want to find out the header hierarchy, e.g. for the anchor with id="123" I would like to get something like [{level: 1, title: "Title"}, {level: 2, title: "Foo"}], similarly for anchor with id="456", I would like to get [{level: 1, title: "Title"}, {level: 2, title: "Foo"}, {level: 3, title: "Bar"}].
My code looks like this so far:
const linkModel: IDictionary<ILinkModelEntry> = {};
const $ = cheerio.load(html);
$("a").each((_i, elt) => {
const anchor = $(elt);
const id = anchor.attr().id;
if (id) {
const parent = anchor.parent();
const parentTag = parent.prop("tagName");
let headerHierarchy: any[] = [];
if (["H1", "H2", "H3", "H4", "H5", "H6"].includes(parentTag)) {
let level = parseInt(parentTag[1]);
headerHierarchy = [{level, text: parent.text()}];
level--;
while (level > 0) {
const prevHeader = parent.prev("h" + level);
const text = prevHeader.text();
headerHierarchy.unshift({level, text});
level--;
}
}
linkModel["#" + id] = {originalId: id, count: count++, headerHierarchy};
}
});
What am I doing wrong, since
const prevHeader = parent.prev("h" + level);
const text = prevHeader.text();
always returns an empty string (i.e. "")?
If I understand correctly, you're looking to capture hierarchy. If your example had another <h1> followed by more <h2> and <h3>s below it, you'd want to pop the stack of parents back down to that new <h1> level for linking future <h2> and <h3> children rather than have an array of all elements back up to that first <h1>Title</h1>.
Here's one approach:
const cheerio = require("cheerio"); // ^1.0.0-rc.12
const html = `
<h1>Title</h1>
<p>Some additional content, can be multiple, various tags</p>
<h2><a id="123"></a>Foo</h2>
<p>Some additional content, can be multiple, various tags</p>
<h3><a id="456"></a>Bar</h3>
<h1>Another Title</h1>
<h2><a id="xxx"></a>Foo 2</h2>
<h3><a id="yyy"></a>Bar 2</h3>`;
const $ = cheerio.load(html);
const result = {};
const stack = [];
[...$("h1,h2,h3,h4,h5,h6")].forEach(e => {
const level = +$(e).prop("tagName")[1];
while (stack.length && level <= stack.at(-1).level) {
stack.pop();
}
if (!stack.length || level >= stack.at(-1).level) {
stack.push({level, title: $(e).text()});
}
if ($(e).has("a[id]").length) {
const id = $(e).find("a[id]").attr("id");
result[`#${id}`] = [...stack];
}
});
console.log(result);
Output:
{
'#123': [ { level: 1, title: 'Title' }, { level: 2, title: 'Foo' } ],
'#456': [
{ level: 1, title: 'Title' },
{ level: 2, title: 'Foo' },
{ level: 3, title: 'Bar' }
],
'#xxx': [
{ level: 1, title: 'Another Title' },
{ level: 2, title: 'Foo 2' }
],
'#yyy': [
{ level: 1, title: 'Another Title' },
{ level: 2, title: 'Foo 2' },
{ level: 3, title: 'Bar 2' }
]
}
If you actually want the whole chain of ancestors linearly back to the first, then remove the while loop (unlikely your intent).

How to get info from object on click

So i made this object and i'm appending to the html. I would like to make a js function that would give me the info from the object upon clicking the element. So when i click element named car it would give me the name car in js.
var ItemCollection =
[
{
Name: 'IVY PARK SHOES',
Price: 160,
Picture: 'https://assets.adidas.com/images/w'
},
{
Name: 'JOGGER SHOES',
Price: 160,
Picture: 'https://assets.adidas.com/images/w_840,h_840,f_'
},
{
Name: 'ULTRABOOST SHOES',
Price: 200,
Picture: 'https://assets.adidas.com/images/w_840,h_840,f_auto,q'
},
{
Name: 'NITE SHOES',
Price: 130,
Picture: 'https://assets.adidas.com/images/w_840,h_840,f_a'
},
];
i know the one bellow will give me the items index but i'd like it to give me name/price or picture. Also the it doesn't have to be alert the alert is just to see if it works.
var g = document.getElementById('Collection');
for (var i = 0, len = g.children.length; i < len; i++) {
(function(index){
g.children[i].onclick = function(){
alert(index);
}
})(i);
}

How do i search 'titles' from array of objects & return only objects that match searchTerm?

bit of a newbie! I am trying to re-populate a carousel of images... based on an array of search results. But really hitting surprising amount of issues.
I'm using JS/Jquery and have, say, an array of objects that exist from my api:
let arrayOfObjects = [
{id: 0, title: 'Beauty & The Beast', img: 'https://imgthing1.com' },
{id: 1, title: 'The Brainiac', img: 'https://imgthing2.com' },
{id: 2, title: 'Mac and Me', img: 'https://imgthing3.com' }
];
Then i have my searchTerm which i want to filter the array down, and return a new array of results from:-
function checkWords(searchTerm, arr) {
let results = [];
let st = searchTerm.toLowerCase();
// **** i map through the array - if the search term (say its 'a' is the same
// as the first character of an object's 'title'... then it stores
// that object in results, ready to be rendered. ****
arr.map((each) => {
if (st === each.title.charAt(0)) {
results.push(each)
}
})
console.log(finalResults);
}
But i can't work out how to keep it matching... based on:
'Bea' vs 'Beauty & The Beast' - pass.
'Beat' vs 'Beauty & The Beast' - fail.
You could use Array#filter and check if the string contains the wanted string at position zero.
let arrayOfObjects = [{ id: 0, title: 'Beauty & The Beast', img: 'https://imgthing1.com' }, { id: 1, title: 'The Brainiac', img: 'https://imgthing2.com' }, { id: 2, title: 'Mac and Me', img: 'https://imgthing3.com' }];
function checkWords(searchTerm, arr) {
let st = searchTerm.toLowerCase();
return arr.filter(each => each.title.toLowerCase().indexOf(st) === 0);
}
console.log(checkWords('bea', arrayOfObjects));

Access data from an array with jquery

Im trying to loop through an array only i cant seem to extract the data from my array...
http://jsfiddle.net/338Ud/
var listTicker = function (options) {
var defaults = {
list: [],
startIndex: 0,
interval: 3 * 1000,
}
var options = $.extend(defaults, options);
var listTickerInner = function (index) {
if (options.list.length == 0) return;
if (!index || index < 0 || index > options.list.length) index = 0;
var value = options.list[index];
options.trickerPanel.fadeOut(function () {
$(this).html(value).fadeIn();
});
var nextIndex = (index + 1) % options.list.length;
setTimeout(function () {
listTickerInner(nextIndex);
}, options.interval);
};
listTickerInner(options.startIndex);
}
var textlist = new Array({
id: 0,
name: 'Antonia Lallement',
title: '\u003cp\u003e\u003cspan\u003eConsultant\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI started as a resourcer at company three months ago so I\u0026rsquo;m a new team member. Sin...',
image: 'antonia.jpg'
}, {
id: 1,
name: 'Camilla Gobel',
title: '\u003cp\u003e\u003cspan\u003eBusiness Manager\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI joined company in 2011. As a multilingual Consultant, my initial focus was the provisi...',
image: 'camilla.jpg'
}, {
id: 2,
name: 'Mark Dorey',
title: '\u003cp\u003e\u003cspan\u003eDiscipline Manager (Process, Subsea, Project, Safety)\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eWhen I joined company I started as a resourcing specialist and worked across Search and ...',
image: 'mark.jpg'
}, {
id: 3,
name: 'Sadia Butt',
title: '\u003cp\u003e\u003cspan\u003eDiscipline Manager (Mechanical, Piping, Structural)\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI couldn\u0026rsquo;t have asked for a better company to work for! After working as a resourc...',
image: 'sadia.jpg'
}, {
id: 4,
name: 'Samantha Linnert',
title: '\u003cp\u003e\u003cspan\u003ePayroll Assistant\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI began at company as an operations assistant learning to spec CVs and post jobs. Shortl...',
image: 'samantha.jpg'
}, {
id: 5,
name: 'Simon Cottenham',
title: '\u003cp\u003e\u003cspan\u003eConsultant, Middle East\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI have been with company for exactly one year now, I never would have believed that I wo...',
image: 'simon.jpg'
}, {
id: 6,
name: 'Vicky Spencer',
title: '\u003cp\u003e\u003cspan\u003ePayroll Manager\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI started my career at company in July 2012 initially covering maternity leave, managing...',
image: 'vicky.jpg'
});
$(function () {
listTicker({
list: textlist,
startIndex: 0,
trickerPanel: $('.textbox'),
interval: 3 * 1000,
});
});
you are adding object to a html .... use . operator to get the actual values
....
options.trickerPanel.fadeOut(function () {
$(this).html(value.id).fadeIn();
//--------^^^----here
}
i am taking id from the object and showing it in the div.. you can add whatever you need there..
$(this).html(value.title).fadeIn(); //to get title
fiddle here
$.each(textlist, function(index, value){
//do stuff with your array
});
Pasting just the diff, i tried to get the data here below.
From the code above.
options.trickerPanel.fadeOut(function () {
$(this).html(value).fadeIn();
});
The diff,
options.trickerPanel.fadeOut(function () {
$(this).html(value.bio).fadeIn();
});
The difference, is value is the entire array object being passed to the fadeOut function, accessing each elements in the array gives the result.

Categories

Resources