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/
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>
This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
How Replace All img src With data-src for Lazy Load Without jQuery
(1 answer)
Closed 1 year ago.
I want to replace src from data-src and I have the script but it's not working properly. Please modify this given script.
This is the script which I want to load before loading images but it's not working properly so please fix this.
var region = document.getElementsByClassName("content");
if (region) {
var img = region.getElementsByTagName("img");
for (var i = 0; i < imgEl.length; i++) {
if (imgEl[i].getAttribute('src')) {
imgEl[i].setAttribute('data-src', imgEl[i].getAttribute('src'));
imgEl[i].removeAttribute('src');
}
}
}
<div class='content'> <img src="img.jpg" alt="img"> </div>
A nice method for do that is using querySelectorAll for get a return of NodeList and can iterate with forEach callback, here an example:
var region = document.querySelectorAll(".content");
//console.log(region);
if (region) {
region.forEach(function(element) {
let img = element.querySelectorAll("img");
img.forEach(function(elementx, index) {
let x = elementx.getAttribute('src');
if (x) {
elementx.dataset.src = x;
elementx.removeAttribute('src');
}
});
});
}
<div class="content">
<p>Abcd</p>
<img src="something.jpg" />
<p>Efgh</p>
<img src="something2.jpg" />
<p>Ijkl</p>
<img src="something3.jpg" />
</div>
<div class="content">
<p>Abcd</p>
<img src="something4.jpg" />
<p>Efgh</p>
<img src="something5.jpg" />
<p>Ijkl</p>
<img src="something6.jpg" />
</div>
var region = document.getElementsByClassName("content");
for (var x = 0; x < region.length; x++) {
var imgs = region[x].getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
if (imgs[i].getAttribute('src')) {
imgs[i].setAttribute('data-src', imgs[i].getAttribute('src'));
imgs[i].removeAttribute('src');
}
}
}
I have an image preview from thumbnails that works on click of thumbnail by changing the preview src. I recently added previous and after navigation buttons. Both systems are working fine yet if I click on a thumbnail and then use the navigation buttons the preview will return to the starting image and not go next or previous. Here's the code to clarify:
//thumbnail click
$(".gallery").click(function() {$("#bigImage").attr("src", $(this).attr("src"));});
//image slider
$( document ).ready(function (){
var slide = [];
$(".gallery").each(function(){
slide.push(this.src);
});
console.log(slide);
$(".galimaslirig").click(function(){
var bigSrc = $("#bigImage").attr("src");
console.log(bigSrc);
var slideCounter = slide.indexOf(bigSrc);
console.log(slideCounter)
if (slideCounter >= slide.length - 1){
slideCounter = -1;
}
$("#bigImage").attr("src", slide[++slideCounter]);
});
$(".galimaslilef").click(function(){
var bigSrc = $("#bigImage").attr("src");
console.log(bigSrc);
var slideCounter = slide.indexOf(bigSrc);
console.log(slideCounter)
if (slideCounter <= 0){
slideCounter = slide.length;
}
$("#bigImage").attr("src", slide[--slideCounter]);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-12 biimdi">
<button class="galimaslilef"><span class="fa fa-arrow-left"></span></button>
<img class="img-fluid" id="bigImage" align="center" src="kids.jpg" width="50%" height="50%" alt="big screen" />
<button class="galimaslirig"><span class="fa fa-arrow-right"></span></button>
</div>
<div class="col-12" id= "imageGallery" align="right">
<img class="gallery" src="./kids.jpg" width="200px" height="200px" alt="kids" />
<img class="gallery" src="./family.jpg" width="200px" height="200px" alt="family" />
<img class="gallery" src="./stance.jpg" width="200px" height="200px" alt="stance" />
<img class="gallery" src="./friends.png" width="200px" height="200px" alt="friends" />
<img class="gallery" src="./woman.jpg" width="200px" height="200px" alt="woman" />
<img class="gallery" src="./jump.jpg" width="200px" height="200px" alt="jump" />
<img class="gallery" src="./man.jpg" width="200px" height="200px" alt="man" />
<img class="gallery" src="./grind.jpg" width="200px" height="200px" alt="grind" />
</div>
I am guessing this is some kind of asynchronous issue in which I am not very good at. As you can see when I console log bigSrc it logs the right src but after assigning its index to slideCounter and console log it the result is always -1 in which I am guessing means undefined. What is happening here?
The previous next issue arises because of this - var bigSrc = $("#bigImage").attr("src"); This returns just the image name like kids.jpg. Where as your array stores images with slide.push(this.src); - this gives full path. So it always returns -1. You can modify the function a little like this.
$( document ).ready(function (){
var slide = [];
$(".gallery").each(function(){
console.log(this.src);
slide.push(this.src);
});
var bigImg = document.getElementById('bigImage'); // big image id
console.log(slide);
$(".galimaslirig").click(function(){
var bigSrc = bigImg.src; // big image source - full path
console.log(bigSrc);
var slideCounter = slide.indexOf(bigSrc);
console.log(slideCounter)
if (slideCounter >= slide.length - 1){
slideCounter = -1;
}
$("#bigImage").attr("src", slide[++slideCounter]);
});
$(".galimaslilef").click(function(){
var bigSrc = bigImg.src; // big image source - full path
console.log(bigSrc);
var slideCounter = slide.indexOf(bigSrc);
console.log(slideCounter)
if (slideCounter <= 0){
slideCounter = slide.length;
}
$("#bigImage").attr("src", slide[--slideCounter]);
});
});
While T.Shah found the problem, the solution was not working "bigSrc" was logging undefined instead of -1 that I had. After doing a little research I used "$(this).attr('src').slice(2,)" in the each function to push it to the array. and then use the same slice method in the thumbnail click function. Here is the working code:
// the click function
$(".gallery").click(function() {
$("#bigImage").attr("src", $(this).attr('src').slice(2,));
});
//image slider
$( document ).ready(function (){
var slide = [];
$(".gallery").each(function(){
slide.push($(this).attr('src').slice(2,));
});
console.log(slide);
$(".galimaslirig").click(function(){
var bigSrc = $("#bigImage").attr("src");
console.log(bigSrc);
var slideCounter = slide.indexOf(bigSrc);
console.log(slideCounter)
if (slideCounter >= slide.length - 1){
slideCounter = -1;
}
$("#bigImage").attr("src", slide[++slideCounter]);
});
$(".galimaslilef").click(function(){
var bigSrc = $("#bigImage").attr("src");
console.log(bigSrc);
var slideCounter = slide.indexOf(bigSrc);
console.log(slideCounter)
if (slideCounter <= 0){
slideCounter = slide.length;
}
$("#bigImage").attr("src", slide[--slideCounter]);
});
})
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;
}
});
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>