Trying to use different array data structure in a jQuery script - javascript

I came across this random image rotator
var theImages = new Array()
theImages[0] = 'img1"' theImages[1] = 'img2"'......
var shuffled = [];
while (theImages.length) {
shuffled.push(theImages.splice(Math.random() * theImages.length, 1));
}
$(document).ready(function(){
//Runs Script each time there is an <li>
$("#news li").each(function(index){
//Puts Image in front of everything in <li>
$(this).prepend('<img src="'+shuffled[index]+'">');
});
});
And I integrated it into a jQuery Carousel. You can see (my fiddle) here. The problem is that the array structure I want to use for the Carousel is different from the rotator's. The rotator uses:
var theImages = new Array()
theImages[0] = 'img1"'
theImages[1] = 'img2"'
theImages[2] = 'img3"'
But I want to use the following for the Carousel because I want to input a link to each picture as well.
var theImages = [
['img1','url_1'],
['img2','url_2'],
['img3','url_3']];
The outcome I'm looking for would be like:
<div id="carousel1">
<div class="1"><img src="img1"></div>
<div class="1"><img src="img2"></div>......
From what I've read, I have to use for in loop to assign the data and can't simply use what the image rotator is using:
$("#carousel1 .1").each(function(index){
$(this).prepend('<a href="'+imgPath+''+shuffled[index]+'"><img
src="'+urlPath+''+shuffled[?url](?url)+'"></a>');
Is that true? Is there any way that allows me to populate the images as well as the urls in the Carousel?

No, never use for ... in for arrays. All you have to do is change
'<img src="'+shuffled[index]+'">'
to
'<img src="'+urlPath+shuffled[index][0]+'">'
since the image path is the first element of the inner array, and the link is the second one.
See Access / process (nested) objects, arrays or JSON for more info.
(I assume imgPath and urlPath are actually defined somewhere and contain URLs. If not, you should remove them.)

Your problem is that your source array (the shuffled values) only contains one value but the final resulting one you want to have pairs of values. That extra data needs to come from somewhere, the computer can't just invent it.
The easiest way to do this is to modify the shuffle code and instead of shuffling single strings shuffle pairs of strings instead.
i.e. something like
var theImages = new Array()
theImages[0] = ['img1"', data1]
theImages[1] = ['img2"', data2]

for(var i=0;i<theImages.length;i++){
newTheImagesArray.push([theImages[i],theImages[i]])
}
This should work for what you want

Related

Setting data info on dynamically created html

I have a JSON response from a server, which returns me a array with 32 objects (in this case). Something like this:
[{object1},{ object2},{ object3}, etc].
Each object have some info that I use to populate an html template. For that, I just use a simple loop:
for(var i = 0; i < api_empresaListar.length; i++)
{
var item = api_empresaListar[i];
var htmls;
htmls = $('...lots of html code');
...
Then it’s just a simple matter of finding/changing the values, and append items on the DOM. Everything works fine. BUT, for some next parts of the code, I would like to access all the info from the object I used to build the html elements (I just show part of the info). So, after searching a lot, I tried to use data, like this:
var tp = htmls.find(".rl_grupo"); // the main div of each html element created in the loop
$(tp).data('key', api_empresaListar[i]); // here, I expected to just insert the object data in each created item.
But when I try it in the console, I got the object info as expected, but always from the last element in the array. Why is that happening? I believe it might be something stupid, but I can’t figure it out.
So, any ideas on how to solve this, or another method to make this work is appreciated. I made it work by setting some "display:none" placeholder html tags and populate those with the info I need later, but looks like a poor solution...
You should not set your htmls variable in the loop. I think that you crush its content every turn, that's why you only have the last item. You should do something like this:
var htmls = $('<div></div>');
for(var i = 0; i < api_empresaListar.length; i++) {
htmls.append($('...lots of html code'));
}
How about setting an index number on each element inside of your html creating code, then iterating over the $('.rl_grupo') elements, like this?
$('.rl_grupo').each(function(){
var index = $(this).data('index');
var currentData = api_empresaListar[index];
$(this).data('key', currentData);
})

Making an array of file paths in JavaScript?

This might be a stupid question, but I can't seem to find an answer. I'm pretty new to Javascript, and I want to know how to declare files/file paths as a variable, so I can put them in an array.
Like, if I have a lot of images in a folder (as in, several hundred) and I want to display certain ones based on the tags the user selects, there must be a way to have those image files in an array so a For loop can cycle through them, right?
(Even better would be if it could somehow parse an int into a filename like [i].png if I have the files named 1.png, 2.png, etc but I don't know if that's possible)
Anyway, basically all I need to know is how to make an array of files, so that "Pictures[245]" refers to "images/small/245.png"
I feel like I must be overlooking something obvious.
There it is:
var Pictures = [];
Pictures.push("/images/small/0.png");
Pictures.push("/images/small/1.png");
Pictures.push("/images/small/2.png");
Then you can get them by calling Pictures[0], Pictures[1], etc.
Notice that array index starts from zero, so if you would use above solution and if you would add images in order, then your image 245.png would be under index 244 not 245.
If you just want to create URL to an image by file name or some identifier, then do not use array, simply use function:
getImageUrl(index) {
return "/images/small/" + index + ".png";
}
Essentially you just want to do.
var picture = []; //Define array pictures
//loop through all pictures
for (i = 0; i < (amount of images); i++) {
picture.push("/images/small/" + i + ".png"); //Add to array
}
Now you can call picture[0] ... picture[1] ... etc...

Accessing an object within an object for jquery/underscore.js

Can't believe this has proven so difficult.
I have the following JSON:
{"1440071374-Bane breathing.jpg":{"filename":"1440071374-Bane
breathing.jpg","alt":"This is bane","primary":true,"caption":"This is
Banecat, the worst enemy of Batcat"}}
I've converted this into an object with the following underscore syntax:
_.each(results, function(r) {
var obj = JSON.parse(r.images)
Pseudo for what I want to do is as follows:
if primary exists and is true {
var img = filename
I'd have thought it was an obvious job of just obj[0].filename but apparently not and I've been stuck on this for awhile now.
Any help is greatly appreciated.
I've come back to the problem after the weekend and I'm noticing the JSON is not being treated as an object:
<%
_.each(results, function(r) {
var a = r.images;
_.isObject(a); // strangely now resulting in false????
_.isString(a); // true
When I echo the JSON onto the page using the underscore syntax <%= r.images %> I get the json I've pasted at the top of this question. Perhaps because the results are coming from a request it needs to be parsed first?
Your JSON is already a object (dictionary). All you need to do is iterate and validate whether primary is true and if it is, assign filename value to var img
var a = {"1440071374-Bane breathing.jpg":{"filename":"1440071374-Bane breathing.jpg","alt":"This is bane","primary":true,"caption":"This is Banecat, the worst enemy of Batcat"}};
for (items in a) {
if (a[items]['primary'] == true) {
var img = a[items]['filename'];
alert(img); // <-- will display 1440071374-Bane breathing.jpg in this example
}
}
Same code in JSFiddle. Play around with different values.
Why don't add src dynamically? Add the following code and it should work. Make sure that you have an <img> element with an unique id
document.getElementById('imgId').src = "example.com/" + img;
I have also edited the code in the same fiddle as above.

How to combine multiple scripts into one?

I've got five of the same scripts that just use five different variables. #video0 to #video4. I'm just not quite sure on how to combine them all so I don't have redundant code. I've been trying to make them all variables
var video= [
$('#video0'),
$('#video1'),
$('#video2'),
$('#video3'),
$('#video4')
];
http://jsfiddle.net/cwfybnzr/
Use each() with the array
var videos = [
$('#video0'),
$('#video1'),
$('#video2'),
$('#video3'),
$('#video4')
];
$(function() {
$.each(videos, function(){
var iframe = $(this)[0];
...
});
});
Isn't it better to create class for those elements? Then it will be possible to iterate through them using simple jQuery syntax: $('.video'). Plus it would not require changing any JavaScript code when new videos will be added.
You can add a class element like videoCSS to all the elements and then loop through them like
$('.videoCSS').each(function(){
var player = $(this);
// your code here
});
This way you can future proof you js code as you can add as many new player/iframes to the HTML with videoCSS class and your js code will still be the same.
Also, I found that in your code you are doing like
var iframe = $('#video0')[0];
var player = $(iframe);
Which means that first you are getting a jquery object using $('#video0'), then you are trying to get a DOM element out of it like $('#video0')[0] and then again you are converting it to a jquery object using $(iframe).
I think there is no need of this much extra processing, you can simply use
var player = $('#video0');
or using my updated code like
var player = $(this);
UPDATED FIDDLE

iterate inside a new JQuery object

I need to pass some html code as a parameter, however, before I pass it, I need to change some src attribute values.
I cannot use lastIndexOf or any of those to modify the html value since I don't know which value the src's will have.
What I'm trying to do then, is to create an object containing the html, and then alter that object only. I don't want to alter the actual webpage.
is this possible??
What I did first was this:
$('[myImages]').each(function() {
var urlImg = "../tmpFiles/fileName" + counter;
$(this).attr('src', urlImg);
counter++;
});
So finally, I had the desired code like this:
myformData = { theChartCode: $('#TheDivContainingTheHTML').html() }
However, this actually changes the image sources on the webpage, which I don't want to.
Then I thought I could create a JQuery object with the html so I could alter that object only like this:
var $jQueryObject = $($.parseHTML($('#TheDivContainingTheHTML').html()));
But now, I can't figure out how to iterate within that object in order to change the src attribute's values of the desired images.
Any help will be really appreciated ;)
There are several ways to do It. First would be creating a clone of target element and use the same on the Fly. You can do like below:
var Elem = $('#TheDivContainingTheHTML').clone();
now do whatever you want like iterate, alter,insert,remove.
var allImages =$(Elem).children("img");
Thanks Much!
Depending on when you want to change the object, solution will be different. Let's pretend you want to change it after you click another element in the page. Your code will look like that :
var clonedHTML;
$('#clickable-element').click(function() {
var $originalHTML = $(this).find('.html-block');
var $cloneHTML = $originalHTML.clone();
$cloneHTML.find('.my-image').attr('src', 'newSrcValue');
clonedHTML = $cloneHTML.clone();
return false; //Prevents click to be propagated
});
//Now you can use `clonedHTML`
The key point here is the clone method : http://api.jquery.com/clone/.
You can clone the elements:
var outerHTML = $collection.clone().attr('src', function(index) {
return "../tmpFiles/fileName" + index;
}).wrapAll('<div/>').parent().html();
You can also use the map method:
var arr = $collection.map(function(i) {
return $(this).clone().attr('src', '...').prop('outerHTML');
}).get();

Categories

Resources