Extract image src from the whole div using Javascript - javascript

Hi I am working in JavaScript. My code is:
<div id="myDiv" onClick="myfn()">
<img src="a.png">
<img src="b.png">
</div>
I want to get the source of the images and store it in the array on click of a button.
Any help ???
myfn() {
var a = new Array();
var mainDivData = document.getElementById('myDiv').innerHTML;
var mainDivData2 = mainDivData.getElementByTag('src');
for(var i =0 ; i<mainDivData2.length; i ++) {
//a[i] = mainDivData2;
alert(a[i]);
}
}
But nothing shown in the alert even alert window doesn't opened.
Any help ???

Pure JavaScript solution:
var imgs = document.getElementById("myDiv").getElementsByTagName("img"),
arr = [];
for (var i = 0; i < imgs.length; i++) {
arr.push(imgs[i].src);
}
console.log(arr);
jQuery solution:
var arr = $("#myDiv img").map(function() {
return this.src;
}).get();
console.log(arr);

Related

How do you use increments?

I am not sure how to use increments.
through a function. i can't get the paragraph to show the array words
<p id= "demo"
var Array = ["hello", "goodbye"];
var mimg = document.getElementById(imageArray[0]);
mimg.setAttribute('src', [index]);
//var ArrayIndex = 0;
function change() {
("src", Array[Index]);
imageIndex++;
if (Index >= Array.length) {
Index = 0;
}
}
Don't forget to use your browser's console, read this article Using Your Browser to Diagnose JavaScript Errors.
Don't use setattribute function, use src attribute.
var myImage = document.getElementById("mainImage");
var imageArray = ["http://lorempixel.com/400/200/sports/1/", "http://lorempixel.com/400/200/sports/2/", "http://lorempixel.com/400/200/sports/3/", "http://lorempixel.com/400/200/sports/4/"];
myImage.src = imageArray[0];
var imageIndex = 0;
function changeImage() {
myImage.src = imageArray[imageIndex];
imageIndex++;
if (imageIndex >= imageArray.length)
imageIndex = 0;
}
window.onload = function() {
setInterval(function() {
changeImage();
}, 1000);
};
<img id="mainImage" />
var myImage = document.getElementById("mainImage");
var imageArray = ["images/1.png","images/2.png","images/3.png","images/4.png"];
var mimg=document.getElementById(imageArray[0]);
mimg.setAttribute('src',photos[index]);
You aren't showing your relevant HTML, but I notice in this section you are getting an element with ID "images/1.png" and setting the src of that element to the value of something in photos[index]. You haven't shown how the photos array is loaded. Do you actually have an element with an ID "images/1.png"?
In your function, you set the src of the mainImage to the values in imageArray rather than the values in the photo array. That may be valid, but since that is different than what you did outside the function, I want to make sure that was intended.
I think you are talking about such solution:
var imageArr=["images/1.png", "images/2.png", "images/3.png", "images/4.png"];
$('#button'). on('click',function(){
var index=(Math.random(0,imageArr.length)*10)
$('#img').attr('src',imageArr[index])
});
Again you question is not clear, thus I think this will help you to get direction.
This should be solution if you are using plain JavaScript
var myImage = document.getElementById("mainImage"),
imageArray = ["images/1.png", "images/2.png", "images/3.png", "images/4.png"],
imageArrayIndex = 0;
myImage.src = imageArray[imageArrayIndex++];
function changeImage () {
myImage.src = imageArray[imageArrayIndex++];
imageArrayIndex = imageArrayIndex >= imageArray.length ? 0 : imageArrayIndex;
}
Make sure that your element is defined as "img".
Here's a solution which sets a data-index attribute on the image to keep track of the selected index. This solution is compatible with down to IE8 and does not use the Jquery library. Run the code snippet below for a test (click the image to go to the next one).
var mimg = document.getElementById('main-image'),
simg = document.getElementById('sec-image')
imgArr = [
'http://placehold.it/50x50/00AAAA',
'http://placehold.it/50x50/AAAA00',
'http://placehold.it/50x50/AA00AA',
];
var loopImages = function(element, imgArray, startAt) {
var index = element.getAttribute('data-index'),
newIndex = 0;
if (!index)
newIndex = ((startAt && startAt < imgArr.length-1) || 0) + 1;
else if (index < imgArr.length-1)
newIndex = parseInt(index) + 1;
element.setAttribute('data-index', newIndex);
element.src = imgArr[newIndex];
};
mimg.addEventListener('click', function(e) {
loopImages(e.target || e.srcElement, imgArr);
});
setInterval(function() {
loopImages(simg, imgArr);
}, 500);
<p>Preview (click to change)</p>
<img id="main-image" src="http://placehold.it/50x50/00AAAA">
<br>
<p>Preview with interval</p>
<img id="sec-image" src="http://placehold.it/50x50/00AAAA">

I'm trying to make a div width expand once clicking on another div

Im trying to make a div expanded once you click on another div. In my case I'm try to make div with some text in it expand when the image is clicked. A link to my JSFiddle - https://jsfiddle.net/txoyuvqn/3/
My javascript that I am using looks like.
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '500px'
whattochange[i].style.transition = 'all 1s'
whattochange[i].style.backgroundColor = 'red'
}
}, false);
However when I click on the class called image it effects all the Text classes, i know it's because were changing the css to all of the text divs, however is there a way to make it only effect the correlating div? Or am I going about creating this in the wrong way?
getElementsByClassName returns an array, not a single element.
divs is an array, and you are correctly using a for loop and the index indicator [i] after your variable name divs.
You need a similar for loop for whattochange.
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '800px';
whattochange[i].style.transition = 'all 1s';
whattochange[i].style.backgroundColor = 'red';
}
}, false);
There may be a better way, but you could do it like this:
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
{
divs[i].addEventListener("click", function()
{
var w = document.getElementById(this.id.replace('img', 'text'));
w.style.width = '800px'
w.style.transition = 'all 1s'
w.style.backgroundColor = 'red'
});
whattochange[i].id = 'text' + i;
divs[i].id = 'img' + i;
}
See the fiddle
Javascript
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '800px';
whattochange[i].style.transition = 'all 1s';
whattochange[i].style.backgroundColor = 'red';
}
}, false);
}
You have to be sure that the elements exist if your JavaScript code depends on them. The reason why your fiddle didnt work was because, you was not loading the script after the body has finished loading.
In your code, One way of achieving this is by putting the <script> tag at the end of the body like this:
<html>
<head></head>
<body>
<script type="text/javascript">
// code here
</script>
</body>
You can also put all your code in a function for the window.onload event or use jQuery.

How to tell which picture was clicked

var pic3 = document.createElement("IMG");
pic3.setAttribute("src", "img/mutantpre.jpg");
pic3.setAttribute("onclick", "display()");
pic3.setAttribute("id", "mutantpre");
pic3.setAttribute("height", "250px");
pic3.setAttribute("width", "150px");
document.getElementById("product4").appendChild(pic3);
Im trying to create a function to set all pictures to hidden when this one is clicked. However from that function I dont know which one was clicked. How do i figure out which one they clicked get the id of it so i can set the visibility of the other ones.
var pic3 = document.createElement("IMG");
pic3.setAttribute("src", "img/mutantpre.jpg");
pic3.setAttribute("onclick", "display('mutantpre')");
pic3.setAttribute("id", "mutantpre");
pic3.setAttribute("height", "250px");
pic3.setAttribute("width", "150px");
document.getElementById("product4").appendChild(pic3);
by passing same id in function of on click you can do this trick
You can also do like this
var pic3 = document.createElement("IMG");
pic3.setAttribute("src", "#");
pic3.setAttribute("onclick", "display()");
pic3.setAttribute("id", "mutantpre");
pic3.setAttribute("height", "250px");
pic3.setAttribute("width", "150px");
document.getElementById("product4").appendChild(pic3);
function display(){
el = document.getElementsByTagName("img");
for(var i =0;i<el.length;i++){
el[i].addEventListener("click",function(e){
alert("the clicked one's id is "+e.target.id);
});
}
}
Check the working Fiddle
Hope this helps!
var images = document.getElementsByTagName('img');
var activeImage = images[0]; // Assuming the first image is active at first
for(var i = 0; i < images.length; i++) {
var image = images[i];
image.onclick = function() {
activeImage.classList.remove("active");
this.classList.add("active");
activeImage = this;
}
}
The display function :
function display(element){
var list = document.getElementsByTagName("img");
for(var i=0; i<list.length ; i++){
list[i].style.opacity = "0";
}
element.style.opacity="1";
}
And in your code you must have this :
pic3.setAttribute("onclick", "display(this)");
Live example
http://jsfiddle.net/W65yA/1/

How to get all img and its attributes?

`
<ul class="flickr-badge-content">
<li class="first">
<img data-photo-attribution="andysouthwales" data-photo-page="http://www.flickr.com/photos/andysouthwales/1212121/" data-photo-title="abcd" data-photo-id="1212121" src="http://farm3.static.flickr.com/2855/1212121_ce6bfd5c38_s.jpg"></img>
</li>
<li>
<img data-photo-attribution="andysouthwales" data-photo-page="http://www.flickr.com/photos/andysouthwales/1263324993173/" data-photo-title="tennn" data-photo-id="1263324993173" src="http://farm8.static.flickr.com/7457/1263324993173_0e3e9745f8_s.jpg"></img>
</li>
<li>..............</ul>.......
I want to get all image and their attributes. Please Help...
You can cycle through all of the images attributes by using
$('img').each(function(currentImage){
console.log(currentImage.data('photo-attribution')); //log some attribute
});
I'm sure that you will figure the rest out.
I have provided you an example which selects all the image tag and gets the source attribute of each of them. You can use this to get whichever attribute you want.
Using JavaScript
var images = document.getElementsByTagName('img');
var srcList = [];//This is just for the src attribute
for(var i = 0; i < images.length; i++) {
srcList.push(images[i].src);
}
Instead of document.getElementsByTagName('img') you could also use the document.images collection.
function allSrc() {
var src = [];
var imgs = document.images;
for (var i=0, iLen=imgs.length; i<iLen; i++) {
src[i] = imgs[i].src;
}
return src;
}
Using Jquery:
var srcList = $('img').map(function() {
return this.src;
}).get();
try
$(document).ready(function () {
var images = $("img");
for (i = 0; i < images.length; i++) {
alert($(images[i]).attr("data-photo-attribution"));
}
});
There you go:
$('.flickr-badge-content li img').each(function(){
var data = $(this).data();
for(var i in data){
$('<li>', {
text: i + ': ' + data[i]
}).appendTo('.flickr-badge-content');
}});
Working Fiddle

loop through an array one time to populate an iFrame then go to another page when loop is finished

I am new to Javascript and I am lost on how to loop through an array of html documents to populate an iFrame one at a time using a click next button. Here is what I have been struggling with
window.onload = loadPages;
function loadPages () {
var frameThem = document.getElementById("frameWrap");
var arr = ["aCard.html", "bCard.html", "cCard.html", "dCard.html"];
for (index = 0;index < arr.length; index++) {
frameThem.src = (arr[index]);
}
};
document.getElementById('nextButton').onclick = loadPages();
This only loads the last html document. I appreciate any help I can get. Thanks.
var index = 0;
var arr = ["aCard.html", "bCard.html", "cCard.html", "dCard.html"];
function loadPages () {
document.getElementById("frameWrap").src = (arr[index]);
index = (index + 1) % arr.length;
};
window.onload = loadPages;
document.getElementById('nextButton').onclick = loadPages();
This code will show them one by one, showing the next one when you click the button.
<!DOCTYPE html>
<html>
<body>
<button id="nextButton">NEXT!</button>
<iframe id="frame1"></iframe>
<script type="text/javascript">
var lastloaded = 0;
window.onload = loadPages;
function loadPages () {
var frame = document.getElementById("frame1");
var arr = ["aCard.html", "bCard.html", "cCard.html", "dCard.html"];
if (lastloaded+1>arr.length){
lastloaded = 0;
}
frame.src = arr[lastloaded];
lastloaded++;
}
document.getElementById('nextButton').onclick = loadPages;
</script>
</body>
</html>

Categories