I want to insert image src with while loop in javascript
$(document).ready(function(){
var i=1;
while(i <= 40)
{
document.getElementByClassName("fruit").src += "path" + i + ".png";
i+=1;
}
});
<img class="img-responsive" src="path/1.png" />
<img class="img-responsive" src="path/2.png" />
<img class="img-responsive" src="path/3.png" />
...
<img class="img-responsive" src="path/40.png" />
How to create this series with javascript
It's better to look at the collection of elements with the class name first, rather than evaluate the collection with each pass through the while loop.
$(document).ready(function(){
var i = 0;
var elementCollection = document.getElementsByClassName('img-responsive');
var max_i = elementCollection.length;
while(i < 40 && i < max_i) {
elementCollection[i].src = "path/" + i + ".png";
i+=1;
}
});
Related
In a given id of a <div> I need to get a list of all the elements which are in that div.
My goal is to get a list of all elements in the given div and loop over them hide everyone except the first one.
Example:
<div id="RandomId">
<img src="src_1" />
<img src="src_2" />
<img src="src_3" />
.
.
.
<img src="src_n" />
</div>
<script>
function handleImages(divID) {
const div = document.getElementById(DivID);
if(div) {
const Elements = // Here, I need the list;
for (let i = 0; i < Elements.length; i++) {
if (i == 0) {
continue;
}
else {
Elements[i].style = "display:block";
}
}
}
return null;
}
</script>
You could also use querySelectorAll:
const Elements = document.querySelectorAll('#RandomId > img')
You need to use Element.children to get the list of elements inside the div.
That's very easy to do when you're using native JavaScript. Use the following:
<script>
function handleImages(divID){
const div = document.getElementById(DivID);
if(div){
const Elements = div.children //Here, I need the list;
for (let i = 0; i < Elements.length; i++){
if (i == 0) { continue; }
else {Elements[i].style = "display:block";}
}
}
return null;
}
</script>
More details about Element.children.
You can use querySelectorAll to get rid of first child as:
function handleImages(id) {
const allChildren = [...document.querySelectorAll(`#${id} > img`)];
allChildren.forEach(
(imgChild, index) =>
(imgChild.style.display = index === 0 ? "block" : "none")
);
}
handleImages("RandomId");
<div id="RandomId">
<img src="https://picsum.photos/200/300" />
<img src="https://picsum.photos/200/300" />
<img src="https://picsum.photos/200/300" />
<img src="https://picsum.photos/200/300" />
</div>
window.onload = choosePic;
var myPix = new Array("img1.jpg", "img2.jpg", "img3.jpg");
function choosePic() {
var randomNum = Math.floor(Math.random() * myPix.length);
document.getElementById("myPicture").src = myPix[randomNum];
document.getElementById("myPicture2").src = myPix[randomNum];
document.getElementById("myPicture3").src = myPix[randomNum];
}
<img src="img.jpg" width="100" height="100" id="myPicture" alt="some image" />
<img src="img.jpg" width="100" height="100" id="myPicture2" alt="some image" />
<img src="img.jpg" width="100" height="100" id="myPicture3" alt="some image" />
<button id="btn" onclick="choosePic()">Click Hear</button>
I want to show 3 different images from the array. and on 4th or 5th click want to show the same pic.
Something like this?
// gather all <img> elements on page
const imgs = document.querySelectorAll('img');
const imgCount = imgs.length;
// the "Click Here" button
const btn = document.getElementById('btn');
// array of randomly generated image URLs
let imgUrls = [];
let urlsLength;
// number of button clicks
let clickCount;
// initialize the page
function initialize() {
clickCount = 0;
// form array of random image urls from 'picsum.photos'
const randomIndex = Math.floor(Math.random() * 100);
for (let i = 0; i < imgCount * 4; i++) {
imgUrls.push(
`https://picsum.photos/id/${randomIndex+i}/100`);
}
urlsLength = imgUrls.length;
// hide all <img> elements
imgs.forEach(img => {
img.src = "#";
img.style.opacity = "0";
});
// enable the "Click Here" button
btn.disabled = false;
}
// handle "Click Here" button
function buttonClick() {
const iUrlRand = Math.floor(Math.random() * urlsLength);
if (++clickCount < 4) {
// show 3 random images
for (let j = 0; j < imgCount; j++) {
const iImg = (iUrlRand + j) % urlsLength;
imgs[j].src = imgUrls[iImg];
imgs[j].style.opacity = "1";
}
} else if (clickCount < 6) {
// show 1 random image, duplicated in 3 elements
imgs[0].src = imgUrls[iUrlRand];
for (let j = 0; j < imgCount; j++) {
imgs[j].src = imgUrls[iUrlRand];
}
}
if (clickCount === 5) {
// disable button to prevent more than 5 clicks
btn.disabled = true;
}
}
window.onload = initialize;
<body style="background-color: #aaa">
<img src="" width="100" height="100" alt="img 0" />
<img src="" width="100" height="100" alt="img 1" />
<img src="" width="100" height="100" alt="img 2" /><br/>
<button id="btn" onclick="buttonClick()">Click Here</button>
<button onclick="initialize()">Reset</button>
</body>
$("#sel1").click(function () {
$("#itemed1").attr("src", "../img/tab_img_01_on.png");
$("#itemed2").attr("src", "../img/tab_img_02.png");
$("#itemed3").attr("src", "../img/tab_img_03.png");
$("#itemed4").attr("src", "../img/tab_img_04.png");
$(this).find("span").addClass("add");
$("#sel2").find("span").removeClass("add");
$("#sel3").find("span").removeClass("add");
$("#sel4").find("span").removeClass("add");
});
$("#sel2").click(function () {
$("#itemed2").attr("src", "../img/tab_img_02_on.png");
$("#itemed1").attr("src", "../img/tab_img_01.png");
$("#itemed3").attr("src", "../img/tab_img_03.png");
$("#itemed4").attr("src", "../img/tab_img_04.png");
$(this).find("span").addClass("add");
$("#sel1").find("span").removeClass("add");
$("#sel3").find("span").removeClass("add");
$("#sel4").find("span").removeClass("add");
});
$("#sel3").click(function () {
$("#itemed3").attr("src", "../img/tab_img_03_on.png");
$("#itemed1").attr("src", "../img/tab_img_01.png");
$("#itemed2").attr("src", "../img/tab_img_02.png");
$("#itemed4").attr("src", "../img/tab_img_04.png");
$(this).find("span").addClass("add");
$("#sel1").find("span").removeClass("add");
$("#sel2").find("span").removeClass("add");
$("#sel4").find("span").removeClass("add");
});
$("#sel4").click(function () {
$("#itemed4").attr("src", "../img/tab_img_04_on.png");
$("#itemed1").attr("src", "../img/tab_img_01.png");
$("#itemed2").attr("src", "../img/tab_img_02.png");
$("#itemed3").attr("src", "../img/tab_img_03.png");
$(this).find("span").addClass("add");
$("#sel1").find("span").removeClass("add");
$("#sel2").find("span").removeClass("add");
$("#sel3").find("span").removeClass("add");
});
Hello This JQuery code is a source that changes the image when you click on the element.
It works fine, but I have a lot of iterations,
so I want to reduce my code. What should I use?
You could use a simple combination of selectors.
See sample here or in CodePen:
$(".selector").click(function () {
let index = $(this).data('index');
$(".selector").find("span").removeClass("add");
$(this).find("span").addClass("add");
$(".imgs").each( function(){
$(this).attr("src", `../img/tab_img_0${$(this).data('index')}.png`);
});
$(`.imgs[data-index="${index}"]`).attr("src", `../img/tab_img_0${index}_on.png`);
});
.add {
font-size: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="selector" data-index="1">Sel 1 <span>sample</span></button>
<button class="selector" data-index="2">Sel 2 <span>sample</span></button>
<button class="selector" data-index="3">Sel 3 <span>sample</span></button>
<button class="selector" data-index="4">Sel 4 <span>sample</span></button>
<img data-index="1" class="imgs" />
<img data-index="2" class="imgs" />
<img data-index="3" class="imgs" />
<img data-index="4" class="imgs" />
Obviously, if you are using n index > 10 you should use the padStart function.
Expendable version of same code.
function pad(v) {
return (v.length === 2 ? v : '0' + v);
}
$('[id^=sel]').click(function() {
var total = 4;
var idNumber = $(this).attr('id').match(/\d+/);
for ( i = 1; i <= total; i++ ) {
$('#itemed' + i).attr('src', '../img/tab_img_' + pad(i) + '.png');
$('#sel' + i).find('span').removeClass('add');
}
$('#itemed' + idNumber).attr('src', '../img/tab_img_' + pad(idNumber) + '_on.png');
$(this).find('span').addClass('add');
});
But I think #SnakeDrak approach is correct
This will work up to selects with the number 9. It will need a little more work to make it work with numbers grater then 9
$("[id^=sel]").click(function () { // match every element where the id starts with "sel"
var idNumber = $(this).attr('id').match(/\d+/); // get the number of given id
// reset all src paths from all given elements
$("#itemed1, #itemed2, #itemed3, #itemed4").attr("src", "../img/tab_img_01.png");
// use the idNumber to concatenate the selector and set the src
$("#itemed" + idNumber).attr("src", "../img/tab_img_0"+idNumber+"_on.png");
// remove the add class to all given elements
$("#sel1, #sel2, #sel3, #sel4").find("span").removeClass("add");
// add the "add" class to $(this) element
$(this).find("span").addClass("add");
});
Please refer below code.
$("[id^=sel]").on('click', function() {
var selectionID = ["sel1", "sel2", "sel3", "sel4"];
var itemID = ["itemed1", "itemed2", "itemed3", "itemed4"];
var selectedButton = $(this).attr("value");
$(this).find("span").addClass("add");
var indexID = selectionID.indexOf(selectedButton) + 1;
$("#itemed" + indexID).attr("src", "../img/tab_img_0" + indexID + "_on.png");
selectionID = selectionID.filter(e => e !== selectedButton);
itemID = itemID.filter(e => e !== itemID[indexID - 1]);
for (var i = 0; i < selectionID.length; i++) {
$("#" + selectionID[i]).find("span").removeClass("add");
$("#" + itemID[i]).attr("src", "../img/tab_img_0" + itemID[i].charAt(itemID[i].length - 1) + ".png");
}
});
.add {
background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button value="sel1" id="sel1"><span>sel1</span></button><br/>
<button value="sel2" id="sel2"><span>sel2</span></button><br/>
<button value="sel3" id="sel3"><span>sel3</span></button><br/>
<button value="sel4" id="sel4"><span>sel4</span></button><br/>
<img src="" id="itemed1">
<img src="" id="itemed2">
<img src="" id="itemed3">
<img src="" id="itemed4">
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to sort LI's based on their ID
I have a div that is dynamically populated with various images and looks something like:
<div id="images">
<img id="img1" src="..." />
<img id="img3" src="..." />
<img id="img2" src="..." />
<img id="img6" src="..." />
<img id="img5" src="..." />
<img id="img4" src="..." />
</div>
Using javascript and jQuery, i need to sort the images into order of ID but i'm struggling. Heres what I've got so far:
var toSort = $('#images').children;
toSort = Array.prototype.slice.call(toSort,0);
toSort.sort(function(a,b){
var aord = +a.id.substr(6);
var bord = +b.id.substr(6);
return aord - bord;
});
var parent = $('#images');
parent.innerHTML="";
for(var i=0, l = toSort.length; i<l; ++i){
parent.appendChild(toSort[i]);
}
How close am I? What am I doing wrong? Thanks guys.
var imgs = $('#images img');
imgs.sort(function(a, b) {
return a.id > b.id;
});
$('#images').html(imgs);
DEMO
OR
var imgs = $('#images img');
imgs.sort(function(a, b) {
return +a.id.replace('img','') - +b.id.replace('img','');
});
$('#images').html(imgs);
DEMO
Edition with your code:
var parent = $('#images'),
children = parent.children(),
toSort = Array.prototype.slice.call(children, 0);
parent[0].innerHTML = ""; //or parent.empty();
toSort.sort(function(a, b) {
var aord = +a.id.substr(3);
var bord = +b.id.substr(3);
return aord - bord;
});
for (var i = 0; i < toSort.length; i++) {
parent.append(toSort[i]);
}
DEMO
var elem = $('#images'),
imgs = elem.find('img');
imgs.sort(function(a, b) {
return a.id.toUpperCase().localeCompare(b.id.toUpperCase());
});
$.each(imgs, function(idx, itm) { elem.append(itm); });
FIDDLE
I think #thecodeparadox version is better but here is your code corrected a little bit. I changed img to span to make it more visible.
http://jsfiddle.net/whnyn/
I use this to retrieve clickable links in a webpage:
javascript:(function(){as=document.getElementsByTagName(%22a%22);str=%22<ul>%22;for(i=0;i<as%20.length;i++){str+=%22<br><a%20href=%22+as[i].href+%22>%22+as[i].href+%22</a>\n%22}str+=%22</as></ul>%22;with(window.open()){document.write(str);document.close();}})()
But how do i retrieve unclickable image links in a web page? i don't have any knowledge in javascript :D
If you are not using any js frameworks like jQuery/ExtJS etc, then you resort to this solutin:
<input type="button" value="Calculate" onclick="checkImages()"/>
Google
<img src="1" /> sss
<span><img src="2" /> sss</span>
<img src="3" />
<img src="4" />
<div id="outputDiv">
</div>
<script type="text/javascript">
function checkImages()
{
var str="<ul>";
var imgs = document.getElementsByTagName("IMG");
var len = imgs.length;
for(var i=0; i<len; i++)
{
var img = imgs[i];
//console.log("Checking" + img);
if(!hasParentAnchor(img))
{
str+="<li><img src="+img.src+"/></li>";
}
}
document.getElementById("outputDiv").innerHTML = str;
}
function hasParentAnchor(el)
{
if(!el.parentNode || !el.parentNode.tagName) return false;
else if(el.parentNode.tagName.toUpperCase() == "A") return true;
else return hasParentAnchor(el.parentNode);
}
</script>