Gathering segmented data via jQuery with FOR loops - javascript

Here's my code (what I'm stuck on is after the jump)
<script language="JavaScript" type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var countThisMany = 4; //how many data-id's I want to count per "section" of images
var finalString = ""; //blank var to be used later, must be defined here.
</script>
<img src="foo.jpg" data-id="id1" data-item="1" /> // just a bunch
<img src="foo.jpg" data-id="id2" data-item="2" /> // of images with
<img src="foo.jpg" data-id="id3" data-item="3" /> // data-* usage to
<img src="foo.jpg" data-id="id4" data-item="4" /> // store two bits
<img src="foo.jpg" data-id="id5" data-item="5" /> // of information
<img src="foo.jpg" data-id="id6" data-item="6" /> // that I'll need
<img src="foo.jpg" data-id="id7" data-item="7" /> // to extract
<img src="foo.jpg" data-id="id8" data-item="8" /> // later on below.
<img src="bar.jpg" data-id="id9" data-item="1" /> // another set of images
<img src="bar.jpg" data-id="id10" data-item="2" />
<img src="bar.jpg" data-id="id11" data-item="3" />
<img src="bar.jpg" data-id="id12" data-item="4" />
<img src="bar.jpg" data-id="id13" data-item="5" />
<img src="bar.jpg" data-id="id14" data-item="6" />
<img src="bar.jpg" data-id="id15" data-item="7" />
<img src="bar.jpg" data-id="id16" data-item="8" />
<script type="text/javascript">
var item_array = $("img").map(function() {
return $(this).attr("data-item");
}).get();
//alert(item_array);
//returns "1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8"
var id_array = $("img").map(function() {
return $(this).attr("data-id");
}).get();
//alert(id_array);
//returns "id1,id2,id3,id4,id5,id6,id7,id8,id9,id10,id11,id12,id13,id14,id15,id16"
for (i=0;i<countThisMany;i++){
finalString=finalString+id_array[i]+';';
}
//alert(finalString);
//returns "id1;id2;id3;id4" -- could be more or less if "countThisMany" is changed to something other than 4
</script>
This entire code is self-contained so feel free to save it as an HTML and uncomment the alerts to see the results.
What I need, however, is a step further. I would like to only collect the data-id of the img tags whose data-item are less than or equal to the variable countThisMany
So the end result of finalString would be "id1;id2;id3;id4;id9;id10;id11;id12". And if countThisMany was changed to 2, for instance, it would be "id1;id2;id9;id10"
I feel as though I am so close but I can't figure out how to only gather the first 4 of the first set of 8 images, and the first 4 of the second set of 8 images. Again, the total amount of images and how many I would need to capture vary, hence the "countThisMany' var.
This is my first post to the amazing stackoverflow community, so I'm excited! Thanks to all contributors ahead of time!

Use filter method
var item_array = $("img").filter(function() {
return parseInt($(this).data("item")) <= countThisMany;
}).map(function() {
return $(this).data('id');
}).get();

var countThisMany = 4;
var item_array = $("img")
.filter(function() {
return parseFloat( $(this).attr("data-item") ) <= countThisMany;
})
.map(function() {
return $(this).attr("data-id");
})
.toArray(); /* instead of get() */
Note that this will return an array. You seem to want a string, so you might want to call .join(',') on the result.

Use $.grep in combination with $.map. I also added a join to array rather than the loop. fiddle: http://jsfiddle.net/brentmn/5yNbE/5/
var countThisMany = 2;
var finalString = "";
var id_array = $.grep($('img'), function(item) {
return ($(item).data('item') <= countThisMany);
}).map(function(item) {
return $(item).data('id')
});
finalString = id_array.join(';');

Related

How to concatenate Javascript variable in HTML image source tag

How do you concatenate a Javascript variable into the url of a HTML image source tag? I have tried .$ANSWER. "$ANSWER" and +$ANSWER+ and none of these are working.
Do I need to use getElementbyID?
I have a folder of images named cat.jpg, dog.jpg, etc and I have a javascript array of these animal names.
One of them is chosen as $ANSWER and I want to then display the image, using the variable $ANSWER.
I have scoured the internet for any example of how to do this but can't find any.
What I have below is my best guess of how to write it, but I get "Not found" in the console log. The picture are in the folder, as this was working in PHP before I rewrote this in Javascript.
<div>
<img id="ANSWER" src='pictures/animals/$ANSWER.jpg' width=80% height=auto >
</div>
<script>
document.getElementById("ANSWER").src='pictures/animals/$ANSWER.jpg';
</script>
Also, if there is an easy way to do this in JQuery, I would love to know.
This is easy enough to do with raw JavaScript; simply ensure that each of the 'string' components are wrapped in quotes, and then make use of the plus sign (+) to concatenate with your variable(s). Note that the variable(s) should not be in quotes; only the supporting string(s) should be.
For example, if you have the variable cat, and want to craft it in the the URL pictures/animals/cat.jpg, you would use 'pictures/animals/' + $ANSWER + '.jpg'.
Also note that your width and height values need to be wrapped in quotes as well, and the initial setting of src is irrelevant, as it is overwritten.
This can be seen in the following:
var $ANSWER = 'cat';
document.getElementById("ANSWER").src = 'pictures/animals/' + $ANSWER + '.jpg';
console.log(document.getElementById('ANSWER').src);
<div>
<img id="ANSWER" width="80%" height="auto">
</div>
For a jQuery-specific solution, you can use the attr() method, passing 'src' as the first parameter, and your combined URL as the second:
var $ANSWER = 'cat';
$("#ANSWER").attr('src', 'pictures/animals/' + $ANSWER + '.jpg');
console.log(document.getElementById('ANSWER').src);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img id="ANSWER" width="80%" height="auto">
</div>
Hope this helps! :)
If $ANSWER is declared in PHP, the rendered HTML/JS won't know about it.
You'd need to do something like this:
<div>
<img id="ANSWER" src='pictures/animals/$ANSWER.jpg' width=80% height=auto >
</div>
<script>
document.getElementById("ANSWER").src='pictures/animals/<?php echo $ANSWER; ?>.jpg';
</script>
Note: I haven't used PHP in ages, so I may be wrong in the specifics of the PHP syntax. Hopefully, you'll get the idea, though.
If it's declared somewhere in the JS, you can concatenate it like some of the other answers here suggested:
<div>
<img id="ANSWER" src='pictures/animals/$ANSWER.jpg' width=80% height=auto >
</div>
<script>
document.getElementById("ANSWER").src='pictures/animals/' + $ANSWER + '.jpg';
</script>
Is this what you are looking for:
var el = document.getElementById("ANSWER");
var images = ['dog', 'cat', 'fish'];
var index = 0;
function setImage() {
var img = images[index];
el.src = `pictures/animals/${img}.jpg`;
index++;
if (index >= images.len) {
index = 0;
}
}
setImage(); // Get the first URL into the img tag
setInterval(setImage, 2000); // Change images every 2 seconds.
<div>
<img id="ANSWER" src="" width="80%" height="auto" />
</div>
Here it is with images online:
var el = document.getElementById("ANSWER");
var images = [
'https://cdn.rentcafe.com/dmslivecafe/UploadedImages/57ffbe5a-055d-43c1-98fa-8be16ba066ca.jpg',
'http://archer.gamebanana.com/img/ico/sprays/kitten2_render.png',
'https://is5-ssl.mzstatic.com/image/thumb/Purple118/v4/71/46/8d/71468d8f-f9f9-cc04-b346-04a8fef0e7f1/source/256x256bb.jpg'];
var index = 0;
function setImage() {
el.src = images[index];
index++;
if (index >= images.len) {
index = 0;
}
}
setImage(); // Get the first URL into the img tag
setInterval(setImage, 2000); // Change images every 2 seconds.
<div>
<img id="ANSWER" src="" width="80%" height="auto" />
</div>

how to get image url from style attribute

i have html DOM like this i want to grab image url.
<img src="constant/spacer.gif" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb">
<img src="constant/spacer.gif" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb">
my expected output: ["https://example1.com/image/image1.png","https://example1.com/image/image1.png"];
right now i'm using this code
arr = [];
$('.images-thumb').each(function(){
arr.push($(this).attr('style')); // furthur i don't know
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<img src="" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb">
<img src="" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb">
Furthur i don't know how to exactly grab
["https://example1.com/image/image1.png","https://example1.com/image/image1.png"];
please help me thanks in advance
You could do:
url = url.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
This will remove url(' and url(" from the beginning of the string if it is present and ") resp. ') from the end.
arr = [];
$('.images-thumb').each(function(){
var $style = $(this).attr('style');
var $url = $style.replace(/^background-image:url\(["']?/, '').replace(/["']?\)$/, '').replace(/\)/, '');
arr.push($url); // further know you know :-P
});
console.log(arr);
You can simply use
var images = document.querySelectorAll('.images-thumb');
var image, arr=[];
for(var i=0; i<images.length;i++){
image = window.getComputedStyle(images[i]).backgroundImage;
arr.push(image.substr(5, image.length-7));
}
console.log(arr);
Pure JS method to grab all the styles of the element.
You can give the image path in src attribute, otherwise the script will be like below
arr = [];
$('.images-thumb').each(function(){
var txt = $(this).attr('style');
first = txt.indexOf('(');
second = txt.indexOf(')');
arr.push(txt.substr(first+1,second-first-1));
});
console.log(arr);
Just check once
Replace the unwanted text with empty string "" :
Example snippet:
arr = [];
$('.images-thumb').each(function() {
arr.push($(this).css("background-image").replace("url(\"", "").replace("\")", ""));
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<img src="" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb">
<img src="" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb">
You can use JQuery css("background-image") selector and regular expression to get the desired result.
arr = [];
$('.images-thumb').each(function(){
arr.push($(this).css("background-image").replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, ''));
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<img src="" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb">
<img src="" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb">

Change picture in an array with button click

I have a question concerning pictures in an array. I am able to change the picture with a click, but only once. This is my code with some example pictures. There are a lot of tutorials on the net but maybe too complex for me so I created a simple thing.
<html>
<head>
<script type="text/javascript">
//here I am creating my array
var myPicture = [
"http://www.bildersuche.org/images/logos/pixabay-logo.png",
"http://www.bildersuche.org/images/logos/123rf-logo.jpg",
"http://www.java2s.com/style/download.png"
]
// this should be the function and I think here is the error
function nextPic() {
myPicture[1] = document.images;
}
</script>
</head>
<body>
<img src="http://www.java2s.com/style/download.png" width="107" height="98" />
<form>
<input type="button" onclick="nextPic()" value="Change image">
</form>
</body>
</html>
The simple question is, what do I have to change in my code to show the second, third, x pic with one click. Or is there an simple jQuery function for it?
Here's a working example: http://jsbin.com/dubuhizucu/edit?html,console,output
so a couple of things..
1) you need a variable to keep track of where you are in your pictures array.
2) on click, increment that variable from step 1. then, check if it's bigger than the length of your pictures array. if it is then we need to reset it back to 0.
3) simply set the src attribute on the image to the URL from your pictures array, setting the index to whatever the value of counter is!
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img id="target" src="http://www.java2s.com/style/download.png" width="107" height="98" />
<input type="button" onclick="nextPic()" value="change image" />
<script>
var target = document.getElementById('target');
var counter = 0;
var myPictures = [
"http://www.bildersuche.org/images/logos/pixabay-logo.png",
"http://www.bildersuche.org/images/logos/123rf-logo.jpg",
"http://www.java2s.com/style/download.png"
];
function nextPic() {
counter += 1;
if (counter > myPictures.length -1) {
counter = 0;
}
target.src = myPictures[counter];
}
</script>
</body>
</html>
Give your img an id: id="img1"
Create a global variable, for example:
var x = 0;
A global variable is declared in the scope of the entire file, meaning it is not surrounded by any functions, loops, if statements, etc. Your array, myPicture is global.
Then in your function:
function nextPic()
Write instead:
function nextPic(){
// Increment x by 1, x = x + 1
x++;
// Check if on last element of array, change x to first
if(x >= myPicture.length) {
x = 0;
}
// Use variable, declared as number, to access img in array
document.getElementById("img1").src = myPicture[x];
}
If we do not check if x is greater than or equal to the array length then once we have iterated through each image we would attempt to access a null value of the array, one that does not exist.
Your example has an array length of 3, therefore it has indices 0-2. We cannot access any index greater than 2, therefore we set x back to 0.
Your nextPic function is a little bit backwards.
Each time nextPic is called, you're setting the second element in your myPicture array equal to document.images. That's not what you want. You want to set the src of the image (document.images[0]) equal to the next image URL, so you need a way to keep track of what image you're working with (currentImageIndex).
Here's a working example:
var myPicture = [
"http://www.bildersuche.org/images/logos/pixabay-logo.png",
"http://www.bildersuche.org/images/logos/123rf-logo.jpg",
"http://www.java2s.com/style/download.png"
];
var currentImageIndex = 0;
function nextPic() {
currentImageIndex = (currentImageIndex + 1) % myPicture.length;
document.images[0].src = myPicture[currentImageIndex];
}
<img src="http://www.java2s.com/style/download.png" width="107" height="98" />
<form>
<input type="button" onclick="nextPic()" value="Change image">
</form>

Shuffle an Array of Images Without Repetitions

I'm trying to shuffle 3 arrays (not together), to create a jigsaw puzzle. Information inside var cells is from when I define each piece etc in my HTML code. When I reload the page, I need one of the three arrays to appear, and need the contents to be in a random order. Splicing isn't getting me anywhere... I sometimes have all the puzzle piece elements, and sometimes one is missing (I know, I know, splicing removes). Any ideas?
var cells = ["c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10", "c11", "c12",];
var imageSet1 = ["./images1/img1-1.jpg", "./images1/img1-2.jpg", "./images1/img1-3.jpg", "./images1/img1-4.jpg", "./images1/img1-5.jpg", "./images1/img1-6.jpg", "./images1/img1-7.jpg", "./images1/img1-8.jpg", "./images1/img1-9.jpg", "./images1/img1-10.jpg", "./images1/img1-11.jpg", "./images1/img1-12.jpg"];
var imageSet2 = ["./images2/img2-1.jpg", "./images2/img2-2.jpg", "./images2/img2-3.jpg", "./images2/img2-4.jpg", "./images2/img2-5.jpg", "./images2/img2-6.jpg", "./images2/img2-7.jpg", "./images2/img2-8.jpg", "./images2/img2-9.jpg", "./images2/img2-10.jpg", "./images2/img2-11.jpg", "./images2/img2-12.jpg"];
var imageSet3 = ["./images3/img3-1.jpg", "./images3/img3-2.jpg", "./images3/img3-3.jpg", "./images3/img3-4.jpg", "./images3/img3-5.jpg", "./images3/img3-6.jpg", "./images3/img3-7.jpg", "./images3/img3-8.jpg", "./images3/img3-9.jpg", "./images3/img3-10.jpg", "./images3/img3-11.jpg", "./images3/img3-12.jpg"];
var imgSet = [imageSet1, imageSet2, imageSet3];
var imgShuffed = imgSet[Math.floor(Math.random() * imgSet.length)];
for (c in cells) {
var index = Math.floor(Math.random() * imgSet.length);
document.getElementById(cells[c]).src = imgShuffed[index];
imgShuffed.splice(index,1);
}
Break the problem down into parts. First of all, lets see about shuffling an array.
The simplest way I can think of to shuffle an array is to keep picking random elements until all of the elements are gone:
function shuffleArray(arr) {
var newarray = [];
while(arr.length > 0) {
var chosenIndex = Math.floor(Math.random() * arr.length); //choose a number thats in the array
var chosenValue = arr[chosenIndex];
newarray.push(chosenValue); //add the new value to the array
arr.splice(chosenIndex, 1); //and "remove" it from the old array by creating a new array without it
}
return newarray;
}
console.log(shuffleArray([1,2,3,4,5])); //example
Next, choose the correct puzzle as you're doing.
var imgSet = [imageSet1, imageSet2, imageSet3];
var chosenSet = imgSet[Math.floor(Math.random()*imgSet.length)];
Then shuffle the chosen set:
var shuffledChosenSet = shuffleArray(chosenSet);
Now, use that shuffled set to finish the job.
What if you'll use a random number as index to fetch image data, and by that assemble new shuffled array?
Of corse you need to check duplications - but you can make it by saving fetched indexes and comparing the new one with them. Am I getting your problem?
This is you made an array but has two dimensions. For using random function you have merge all your array in an one dimenson array. I hope it helps
var sampleArray = [1,2,3,4,5];
var arrayTemp = [];
for (var i = sampleArray.length;i>=0;i--){
var temp = Rand100()%i;
arrayTemp.push(sampleArray[temp]);
sampleArray.splice(temp,1);
};
console.log(arrayTemp);
Above example gives you an array with random entries of the previous one.This gives you random entries without any duplicate entry and within constant time complexity.
Here is the demo : http://jsfiddle.net/patelmit69/tjmvqajL/
var cells = ["c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10", "c11", "c12",];
var indexes = new Array();
var imageSet1 = ["http://dummyimage.com/100x100/000/fff&text=img11", "http://dummyimage.com/100x100/000/fff&text=img1-2.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-3.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-4.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-5.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-6.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-7.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-8.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-9.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-10.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-11.jpg", "http://dummyimage.com/100x100/000/fff&text=img1-12.jpg"];
var imageSet2 = ["http://dummyimage.com/100x100/000/fff&text=img11", "http://dummyimage.com/100x100/000/fff&text=img2-2.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-3.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-4.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-5.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-6.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-7.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-8.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-9.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-10.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-11.jpg", "http://dummyimage.com/100x100/000/fff&text=img2-12.jpg"];
var imageSet3 = ["http://dummyimage.com/100x100/000/fff&text=img11", "http://dummyimage.com/100x100/000/fff&text=img3-2.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-3.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-4.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-5.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-6.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-7.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-8.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-9.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-10.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-11.jpg", "http://dummyimage.com/100x100/000/fff&text=img3-12.jpg"];
var imgSet = [imageSet1, imageSet2, imageSet3];
alert(imgSet.length);
var imgShuffed = imgSet[Math.floor(Math.random() * imgSet.length)];
for (c in cells) {
var index = Math.floor(Math.random() * imgShuffed.length);
document.getElementById(cells[c]).src = imgShuffed[index];
imgShuffed.splice(index,1);
}
<img id="c1" src='' />
<img id="c2" src='' />
<img id="c3" src='' />
<img id="c4" src='' />
<img id="c5" src='' />
<img id="c6" src='' />
<img id="c7" src='' />
<img id="c8" src='' />
<img id="c9" src='' />
<img id="c10" src='' />
<img id="c11" src='' />
<img id="c12" src='' />

Javascript move picture to the right where the first goes to the back comes to the front with the click of a button

I am trying to create a JavaScript code that has 3 images up when a button is pushed it looks like they are all moving right. So far I am super lose on the JavaScript part of the code. I can't get it to move, or the button to work.
HTML:
<head>
<script src="switchright.js"> </script>
<body>
<h1 style="text-align:center">Image Switcher</h1>
<center>
<img src="../images/smile.png" id=smile>
<img src="../images/plain.png" id=plain>
<img src="../images/wink.png" id=wink>
<br>
<button type="button" id=theButton>Switch Right</button>
</center>
</body>
</head>
Javascript:
theButton.onclick = function pictureChange(){
document.getElementById('smile').src="../images/wink.png";
}
theButton.onclick = function pictureChange(){
document.getElementById('plain').src="../images/smile.png";
}
theButton.onclick = function pictureChange(){
document.getElementById('wink').src="../images/smile.png";
}
As I understood - you have 3 images in a row and you want to change their sources circularly by clicking the button.
Hope this helps ( by the way - I think you should embrace the value of id attribute in double quotes )
// this will iterate from 0 to 2 and represents
// the current position of wink
var position = 0;
// save the links to files in an array
var images = ["../images/wink.png", "../images/smile.png", "../images/smile.png"];
// document.getElementById() are expensive in time
// so better to save the references to the objects
// and not find them every click
var smile = document.getElementById('smile');
var plain = document.getElementById('plain');
var wink = document.getElementById('wink');
theButton.onclick = function() {
// here you now depend on the position values that
smile.src = images[position % 3];
plain.src = images[(position + 1) % 3];
wink.src = images[(position + 2) % 3];
// increments the position variable and checks
// that it deosn't become beggier that 2
position++;
if (position > 2) {
position = 0;
}
}
Please mind that you can change the sources in the images array ( if there would be some issues with that ).
Switch the sources in just one function like this:
window.slide = function(){
var store = document.getElementById('wink').src;
document.getElementById('wink').src = document.getElementById('plain').src;
document.getElementById('plain').src = document.getElementById('smile').src;
document.getElementById('smile').src = store;
}
.small {
width: 25px;
height: 25px;
}
<h1 style="text-align:center">Image Switcher</h1>
<center>
<img class="small" src="http://www.costarricense.cr/pagina/radiogigante/index_files/image007.gif" id="smile">
<img class="small" src="http://www.skip-hop.co.uk/images/skip-hop-number-2.gif" id="plain">
<img class="small" src="http://upload.wikimedia.org/wikipedia/commons/e/e7/L3lo.gif" id="wink">
<br>
<button type="button" onclick="slide()">Switch Right</button>
</center>

Categories