Checking Multiple Image Sources- Javascript - javascript

I have a table of 4 images that change on click. I was wondering how I could check to see if/when all images in the table are the same image source. I am stuck trying to figure out a way to check all image sources in the table. Any advice is appreciated!
HTML:
<table>
<tr>
<td>
<img id="pos1" src="slicedImg_01.gif" onclick="change(1)" />
<img id="pos2" src="slicedImg_02.gif" onclick="change(2)" />
</td>
<tr>
<td>
<img id="pos3" src="slicedImg_03.gif" onclick="change(3)" />
<img id="pos4" src="slicedImg_04.gif" onclick="change(4)" />
</td>
</tr>
</tr>
</table>
JS:
var v = document.getElementById("pos" + clicked_img).src = "slicedImg_0" + rNum + ".gif";
//var elems = document.getElementsByName.images("f")[0].src;
//alert(elems);
if (document.getElementById("pos1").src == v){
if (document.getElementById("pos2").src == v){
if (document.getElementById("pos3").src == v)
Don't mind my trial and error attempts on the page.

Try running this where it makes sense, the src parameter can be removed if the matching src you're looking to check is static.
function checkSameSrc(src){
return document.querySelector('src=[" + src + "]').length === 4;
}

If jQuery is allowed, a quick Fiddle as example:
var image_array = $("img").map(function () {
return $(this).attr("src");
});
images = $.unique(image_array);
alert(images.length);
In case images.length is 1, there's only 1 unique image source. When you change one of the image sources in the fiddle to one of the other images and run the fiddle again, the alert will give you 3 instead of 4 etc.
image_array is created using the map()-function, pushing the src of each image into the array. The unique()-function removes all double entries from this array.
References: http://api.jquery.com/jquery.unique/, http://api.jquery.com/jquery.map/
And the same with pure Javascript:
var elements = document.getElementsByTagName('img');
var imageArray = new Array();
for (var i=0; i<elements.length; i++) {
imageArray[i] = new Image();
imageArray[i] = elements[i].src;
}
function getUnique(element)
{
return element.reduce(function(a,b){if(a.indexOf(b)<0)a.push(b);return a;},[]);
}
alert(getUnique(imageArray).length);
Fiddle with both versions and one double image: Fiddle
Reference for the nice one-liner used in getUnique(): Remove Duplicates from JavaScript Array, see answer by Christian Landgren.

Related

Replace with RegEx does not update source value

i have a site where i paste my entire source code into a box and update all the td tags with a background color if there isnt currently a "bgcolor" attribute.
I've been messing with this for some time but i can't get my ogSource to update. I've tried many ways such as assigning new variables, returns etc etc. No luck.
the below code properly scans for the appropriate td and adds the background color, it just doesnt apply it to the ogSource. I've removed all my other code to make this as basic as possible.
Can anyone assist with this?
Thanks in advance.
var ogSource = '<table id="test1"> <tr> <td> <table id="test2"> <tr> <td> </td> </tr> </table></td> </tr> </table>'
ogSource.replace(/\<td(.*?)\>/g, function(matches) {
if (!matches.includes('bgcolor')) {
var idx = matches.lastIndexOf(">");
if (idx > -1) {
matches = matches.substr(0, idx) + " bgcolor='pink'" + matches.substr(idx);
}
}
});
console.log(ogSource);
EDIT/UPDATE
After a lot of messing around- this was a solution that was able to capture all the source code pasted and make the modification needed.
ogSource = ogSource.replace(/\<td(.*?)\>/g, function( matches , i ) {
var idx = matches.lastIndexOf(">");
if (idx > -1) {
if (!matches.includes('bgcolor')) {
ogSource = matches.substr(0, idx) + " bgcolor='pink'" + matches.substr(idx);
} else {
ogSource = matches;
}
} return ogSource;
});
console.log(ogSource);
My initial answer was off the mark but quite a bit, however, I think regex in general may not be the best solution due to the amount of edge cases present and the DOMParser might be a better solution for this.
Essentially, you pass the html string into the DOMParser method parseFromString and store that in a variable, then select all td elements and check if they have a bgColor attribute, if they don't, give them one, then output the new DOM string.
Here's an example:
const domParser = new DOMParser();
const DOM = domParser.parseFromString(`<table id="test1"> <tr> <td> <table id="test2"> <tr> <td> </td> </tr> </table></td> </tr> </table>`, "text/html");
// Find all tds
const tds = DOM.querySelectorAll("td");
for(let i = 0; i < tds.length; i++) {
let currentTD = tds[i];
if(!currentTD.hasAttribute("bgColor")) {
currentTD.setAttribute("bgColor", "someValue");
}
}
console.log(DOM.body.innerHTML); // If you only want to return the table content
console.log(DOM.querySelector("html").innerHTML); // If you want all of the html code that was added

select images as per choice and display their name as an alert in javascript

I am new here, I have generated 5 images from an array. Now I want to select those images as we select using checkbox (means i can select 1 image or 2 image or more as per choice). After selecting I want to display their name as an alert that you have selected these images. Please guide me because i am new in javascript. Thanks in advance.
It's not entirely clear what an acceptable output is but here is something which accumulates selected photos and displays the image src for the selected photos.
var PhotoSrcArray = [
"http://placekitten.com/g/60/60",
"http://placekitten.com/70/60",
"http://placekitten.com/g/60/70",
"http://placekitten.com/70/70",
"http://placekitten.com/g/80/80"
];
for(var i = 0; i < PhotoSrcArray.length; i++){
$("#imgs").append('<li><label><input type="checkbox"></input><img src="'+PhotoSrcArray[i] + '" data-index="'+(i+1).toString() + '"/></label></li>');
}
var myArray = [];
$("li input").change(function(event){
if (this.checked){
myArray.push($(event.currentTarget).next('img').attr('data-index'));
}
else {
var indexOfPhoto = myArray.indexOf($(event.currentTarget).next('img').attr('data-index'));
if (indexOfPhoto > -1){
myArray.splice(indexOfPhoto, 1);
}
}
myArray.sort();
$("#output").html( myArray.join(' '));
//or alert it if you'ld like
});
Here is a working fiddle here.
This is the working JsFiddle.
You can try this function, it will bind a checkbox to an image:
function bind_checkbox_image(checkboxId, imageId)
{
document.getElementById(checkboxId).onchange = function () {
alert(document.getElementById(imageId).getAttribute("title"));
};
}
The image should have a title and a change on the checkbox will show that title:
<img id="myimage" title="the image text" src="..." />
<input type="checkbox" id="mycheckbox" />
You can now bind those:
bind_checkbox_image("mycheckbox", "myimage");
EDIT: bugfix inverted ids of checkbox and image

How to delete a created element in JavaScript?

Hello I have a piece of code that allows me to add an author.
I have a problem, I can't seem to delete the created node in my table
This is the worst frustration in my life. I could not seem to delete it.
I also have notice that every time I inspected the element I could not see the
new created element from the source. But when I view it on firebug I can actually see it there.
Adding an input element and appending it on the table works fine for me.
I am just very new to JavaScript and to this web thingy and deleting a CREATED ELEMENT via .createElement is where I am stuck at.
here is my code
<script>
var ctr = 1;
function showTextBox()
{
// is the table row I wanted to add the element before
var target = document.getElementById('bef');
var tblr = document.createElement('tr');
var tbld1 = document.createElement('td');
var tbld2 = document.createElement('td');
var tblin = document.createElement('input');
tblin.name = 'Author' + ctr;
tblin.id = 'Author' + ctr;
tblin.placeholder = 'add another author';
tbld1.appendChild( document.createTextNode('Author' + ctr ) );
tbld2.appendChild( tblin );
tblr.appendChild( tbld1 );
tblr.appendChild( tbld2 );
target.parentNode.insertBefore( tblr , target );
ctr++;
}
function hideTextBox()
{
var name = 'Author'+ctr;
var pTarget = document.getElementById('tbhold');
var cTarget = document.getElementById( name );
alert( cTarget ); // this one return null? Why? I have created id="Author1"
// viewing this code on source make the created elem to not appear
}
</script>
Am I doing something wrong? I really need help. This is for my project at school.
Is there any way I could delete it. I created that node and I want it to be deleted when I click something.
Also I prefer to stay with JS not with JQuery or other JStuff and I am disregarding compatibility for now because this is just a sample in my dummy form. I will deal on that later.
EDIT
In case you need the actual form here it is
<form enctype="multipart/form-data" action="process/" method="POST" />
<h3>Book Upload</h3>
<table border="2" id='tbhold'>
<tr>
<td>Title</td>
<td><input type="text" id="book_title" name="book_title" /></td>
</tr>
<tr>
<td>Author</td>
<td><input type="text" id="book_author" name="book_author" /></td>
</tr>
<tr id="bef">
<td colspan="2">
add author
remove
</td>
</tr>
</table>
</form>
Thank you very much!
Try this function:
function removeElements(elements){
for(var i = 0; i < elements.length; i++){
elements[i].parentNode.removeChild(elements[i]);
}
}
Then you can do this:
removeElements(document.querySelectorAll('#tbhold tr'));
function hideTextBox(){
var name = "Author" + (ctr - 1);
var pTarget = document.getElementById('tbhold');
var cTarget = document.getElementById(name);
var tr = cTarget.parentNode.parentNode;
tr.parentNode.removeChild(tr);
ctr = ctr - 1;
}
Here is a demo
every time I inspected the element I could not see the new created element from the source. But when I view it on firebug I can actually see it there.
If you change the DOM, you of course do not change the HTML source markup. Only the DOM inspector will show you the changes.
var name = 'Author'+ctr;
var cTarget = document.getElementById( name );
alert( cTarget ); // this one return null? Why? I have created id="Author1"
Yes, you created it using your showTextBox function. But that did also increment the ctr to 2, so that you now are looking for Author2 which obviously does not exist. So put a ctr--; before it and it should work.

Script to display an image selected at random from an array on page load

I'm using a script on the homepage of a website for a photographer which displays an image selected at random from an array. I have found two different scripts which perform this function. I'd like to know which script is preferable and if it has been written correctly or can be improved. I wonder if it is possible to include a function that would prevent the same image from loading twice until all of the images in the array have been used. Thanks for taking a look.
Version 1
<script type="text/javascript">
<!--
var theImages = new Array()
theImages[1] = 'portrait/fpo/01.jpg'
theImages[2] = 'portrait/fpo/02.jpg'
theImages[3] = 'portrait/fpo/03.jpg'
theImages[4] = 'portrait/fpo/04.jpg'
theImages[5] = 'portrait/fpo/05.jpg'
theImages[6] = 'portrait/fpo/06.jpg'
theImages[7] = 'portrait/fpo/07.jpg'
theImages[8] = 'portrait/fpo/08.jpg'
theImages[9] = 'portrait/fpo/09.jpg'
theImages[10] = 'portrait/fpo/10.jpg'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.write('<img src="images/'+theImages[whichImage]+'">');
}
// -->
</script>
<table cellpadding="0" cellspacing="0" border="0" height="100%" width="100%">
<tr valign="middle"><td align="center">
<script type="text/javascript">showImage();</script>
</td></tr>
</table>
Version 2
<script type="text/javascript">
<!--
var ic = 11; // Number of alternative images
var xoxo = new Array(ic); // Array to hold filenames
xoxo[0] = "images/portrait/fpo/01.jpg"
xoxo[1] = "images/portrait/fpo/02.jpg"
xoxo[2] = "images/portrait/fpo/03.jpg"
xoxo[3] = "images/portrait/fpo/04.jpg"
xoxo[4] = "images/portrait/fpo/05.jpg"
xoxo[5] = "images/portrait/fpo/06.jpg"
xoxo[6] = "images/portrait/fpo/07.jpg"
xoxo[7] = "images/portrait/fpo/08.jpg"
xoxo[8] = "images/portrait/fpo/09.jpg"
xoxo[9] = "images/portrait/fpo/10.jpg"
xoxo[10] = "images/portrait/fpo/11.jpg"
function pickRandom(range) {
if (Math.random)
return Math.round(Math.random() * (range-1));
else {
var now = new Date();
return (now.getTime() / 1000) % range;
}
}
// Write out an IMG tag, using a randomly-chosen image name.
var choice = pickRandom(ic);
// -->
</script>
<table cellpadding="0" cellspacing="0" border="0" height="100%" width="100%">
<tr valign="middle"><td align="center">
<script type="text/javascript">document.writeln('<img src="'+xoxo[choice]+'" >');</script>
</td></tr>
</table>
This code will load images randomly and his respective link to load.
<html>
<head/>
<title>Jorgesys Android</title>
<script type="text/javascript">
var imageUrls = [
"http://stacktoheap.com/images/stackoverflow.png"
, "http://stacktoheap.com/images/stackoverflow.png"
, "http://stacktoheap.com/images/stackoverflow.png"
, "http://stacktoheap.com/images/stackoverflow.png"
, "http://stacktoheap.com/images/stackoverflow.png"
, "http://stacktoheap.com/images/stackoverflow.png"
];
var imageLinks = [
"http://www.stackoverflow.com"
, "http://www.reforma.com"
, "http://www.nytimes.com/"
, "http://www.elnorte.com/"
, "http://www.lefigaro.fr/international/"
, "http://www.spiegel.de/international/"
];
function getImageHtmlCode() {
var dataIndex = Math.floor(Math.random() * imageUrls.length);
var img = '<a href=\"' + imageLinks[dataIndex] + '"><img src="';
img += imageUrls[dataIndex];
img += '\" alt=\"Jorgesys Android\"/></a>';
return img;
}
</script>
</head>
<body bgcolor="black">
<script type="text/javascript">
document.write(getImageHtmlCode());
</script>
</body>
</html>
Decided to make it an answer.
FYI... You're missing one of your pictures in the first version, fyi.
I would go with 2. 1 is loading all of the images up front (more useful if you'll be changing images, doing a slide-show type thing). So it uses more bandwidth and will make your page load slower.
2 looks fine but I might change pickRandom(ic) to pickRandom(xoxo.length) so you don't have to forget about updating ic as you add more images.
You would probably want either to create a cookie for the user (lastImageIndex) to loop through the items. If cookies aren't available, just use a random image. Otherwise, start at a random image. Then each time accessed with the cookie increment. When you reach the length, go back to 0.
function getCookieValue(choice){
// read cookie here, if found, parseInt(cookieValue,10) and assign to choice
// Then return choice (either original value or updated)
return choice;
}
var choice = pickRandom(xoxo.length);
choice = getCookieValue(choice);
// Check if it correspond to an image
if (choice >= xoxo.length) choice = 0;
// Store the cookie here. Store choice++
That description is slightly different than what you asked for, since its per user, but I'd bet it gives you more the result you are looking for.

Looping over Array Elements By Calling them by Id

How do I loop over an Array which has 5 elements. I have 5 elements with ids like imgone, imgtwo, imgthree, imgfour, imgfive.
var ids =
[
"#imgone",
"#imgtwo",
"#imgthree",
"#imgfour",
"#imgfive"
];
for (var i = 0; id = ids[i]; i++)
{
$(id).click(function() {
$("#cell1,#cell2,#cell3,#cell4,#cell5").hide();
$("#cell" + (i+1)).show();
});
}
});
Then I have an 5 a tag elements like
<img src ="myimage1" />
<img src ="myimage2" />
<img src ="myimage3" />
<img src ="myimage4" />
<img src ="myimage5" />
cell1 , cell2, et-al are my blocks that I need to show/hide onclick of a elements.
btw this code always hides all the cell blocks and shows cell6, which does not exist in my code.
I mean $("#cell" + (i+1)).show(); never takes values of i as 0, 1 , 2 , 3 or 4.
So how do I iterate over an array and show hide my cells. I think something is wrong with this line of code $(id).click(function() but can't figure out what???
This is a closure issue, the variable i points to the i used in the loop, and at the time of execution it is always 6.
use this code instead
for (var i = 0; id = ids[i]; i++)
{
var fnc = function(j){
return function() {
$("#cell1,#cell2,#cell3,#cell4,#cell5").hide();
$("#cell" + (j+1)).show();
};
}(i);
$(id).click(fnc);
}
For more on javascript closures see How do JavaScript closures work?
you could jquerify it :
var ids =
[
"#imgone",
"#imgtwo",
"#imgthree",
"#imgfour",
"#imgfive"
];
$(ids.join(,)).each(function(i){
$(this).click(function(){
$("#cell1,#cell2,#cell3,#cell4,#cell5").hide();
$("#cell" + (i+1)).show();
});
});

Categories

Resources