Using DOM to figure out how many images are on my page - javascript

I'm trying to use the DOM to find out how many images on are my page. I need to write code that will check my page to see how many images there are and store them to a variable. I'm not sure how to write this code but I know you need to search the code for all tags.
<body>
<div id="main_content">
<div id="image_selection">
<script type="text/javascript">
</script>
</div>
<div id="images">
<h3>Some Images</h3>
<p><img src="firetruck.jpg" > |
<img src="baseball.jpg" > |
<img src="soccer_ball.jpg" >
</p>
</div><!-- end of 'images' div -->
</div><!-- end of 'main content' div -->

var numberOfImgTags = document.getElementsByTagName('img').length
try this.

To find all the <img> elements on the page, and assign the resulting NodeList to a variable:
// (returns live HTMLCollection):
let allImages1 = document.images;
// or (returns (static, non-live) NodeList):
let allImages2 = document.querySelectorAll('img');
// or (returns (live) HTMLCollection):
let allImages3 = document.getElementsByTagName('img');
To find out how many <img> elements were found simply access the length property of the NodeList, for example:
let totalNumberOfImages = allImages1.length;
To demonstrate the difference between 'live' and 'static' collections:
Using: document.images:
let images = document.images,
counter = document.querySelector('.count');
counter.textContent = images.length;
Array.from(images).forEach(
(el) => {
el.addEventListener('click', (evt) => {
evt.target.remove();
counter.textContent = images.length;
});
})
body {
display: grid;
grid-template-columns: repeat(3, 200px);
}
span.count {
grid-column: 1 / -1;
background-color: limegreen;
text-align: center;
font-weight: bold;
}
<img src="https://placekitten.com/200/200" />
<img src="https://placekitten.com/200/200" />
<img src="https://placekitten.com/200/200" />
<img src="https://placekitten.com/200/200" />
<img src="https://placekitten.com/200/200" />
<span class="count"></span>
JS Fiddle demo.
Using document.querySelectorAll('img'):
let images = document.querySelectorAll('img'),
counter = document.querySelector('.count');
counter.textContent = images.length;
Array.from(images).forEach(
(el) => {
el.addEventListener('click', (evt) => {
evt.target.remove();
counter.textContent = images.length;
});
})
body {
display: grid;
grid-template-columns: repeat(3, 200px);
}
span.count {
grid-column: 1 / -1;
background-color: limegreen;
text-align: center;
font-weight: bold;
}
<img src="https://placekitten.com/200/200" />
<img src="https://placekitten.com/200/200" />
<img src="https://placekitten.com/200/200" />
<img src="https://placekitten.com/200/200" />
<img src="https://placekitten.com/200/200" />
<span class="count"></span>
JS Fiddle demo.
Using document.getElementsByTagName('img'):
let images = document.getElementsByTagName('img'),
counter = document.querySelector('.count');
counter.textContent = images.length;
Array.from(images).forEach(
(el) => {
el.addEventListener('click', (evt) => {
evt.target.remove();
counter.textContent = images.length;
});
})
body {
display: grid;
grid-template-columns: repeat(3, 200px);
}
span.count {
grid-column: 1 / -1;
background-color: limegreen;
text-align: center;
font-weight: bold;
}
<img src="https://placekitten.com/200/200" />
<img src="https://placekitten.com/200/200" />
<img src="https://placekitten.com/200/200" />
<img src="https://placekitten.com/200/200" />
<img src="https://placekitten.com/200/200" />
<span class="count"></span>
JS Fiddle demo.
Note that we (attempt to) update the count in the same way in each demo, simply accessing the length property of the images variable; the variable is updated, and is therefore 'live,' when using document.images and document.getElementsByTagName(), but it remains unchanged, and therefore 'static,' when using document.querySelectorAll():
References:
document.getElementsByTagName().
document.images.
document.querySelectorAll().
HTMLCollection.

jQuery will return a collection of elements that match a selector. That's all you need to just count: $('img').length
That's how your current code works:
$('img').attr('height','50px').attr('width','50px');
This will run an implicit loop over the elements of the collection and set its attributes.

$('img').length will give you total count that exist at the time you run it

Related

Resizing 3 images with javascript

I need to resize 3 images with javascript. How can i do that without having an ID and without having possibility to add one?
I have tried this but i don t know how to select all images(i need to set the width to 50px).
let images=document.querySelector('img');
images.setAttribute("width",50);
Is document.querySelectorAll() what you're looking for? document.querySelectorAll() will select all elements matching a certain selector, not just the first.
In your case, it might be
let images=document.querySelectorAll('img');
images.forEach(img => img.setAttribute("width",50));
If you can't use CSS to change the image width pick up the images with querySelectorAll and then iterate over the node list of images and change the width of each one.
const images = document.querySelectorAll('img');
images.forEach(image => image.setAttribute('width', '50px'));
<img src="https://dummyimage.com/100x100/000/fff" />
<img src="https://dummyimage.com/100x100/000/fff" />
<img src="https://dummyimage.com/100x100/000/fff" />
You can do it with querySelectorAll
changeSize = () => {
let images = document.querySelectorAll('img');
for (let i = 0; i < images.length; i++) {
images[i].style.width = "100px";
}
}
originSize = () => {
let images = document.querySelectorAll('img');
for (let i = 0; i < images.length; i++) {
images[i].removeAttribute("style");
}
}
.images {
display: flex;
}
.images img {
margin: 1em 1em 0 0;
}
<button onclick="changeSize()">Change Size</button>
<button onclick="originSize()">Origin Size</button>
<div class='images'>
<img src="https://cdnp2.stackassets.com/b1284961a6fbcbcfabe6f69c2ae4219ff6daa5e0/store/opt/596/298/1ca89e578fc4e326fe08196758c1688929acc8c5eeb8572e2282628cad78/product_30565_product_shot_wide.jpg" />
<img src="https://cdnp2.stackassets.com/b1284961a6fbcbcfabe6f69c2ae4219ff6daa5e0/store/opt/596/298/1ca89e578fc4e326fe08196758c1688929acc8c5eeb8572e2282628cad78/product_30565_product_shot_wide.jpg" />
<img src="https://cdnp2.stackassets.com/b1284961a6fbcbcfabe6f69c2ae4219ff6daa5e0/store/opt/596/298/1ca89e578fc4e326fe08196758c1688929acc8c5eeb8572e2282628cad78/product_30565_product_shot_wide.jpg" />
</div>

How can i make a different counter for each photo in js? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm having problems with counter in js, i've made 3 img tags with different id's, but having difficulties what to put in if statement for each counter? How can i see which photo has been clicked?
var count = 0;
function promptImg() {
var count1 = document.getElementById(test1)
var count2 = document.getElementById(test2)
var count3 = document.getElementById(test3)
}
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg()" src="rosa-avon-crvena-ajevke-52-373-standard-1.png">
</div>
<div class="2">
<img id="test2" onclick="promptImg()" src="gerbera.jpg">
</div>
<div class="3">
<img id="test3" onclick="promptImg()" src="gipsofila.jpg">
</div>
</div>
If you want to know how to determine which image was clicked, make sure you pass this into the function assigned to the onclick attribute.
To keep track of click frequency, you can use object or a Set to store the associated count with the ID of the image.
const counter = { };
function promptImg(img) {
counter[img.id] = (counter[img.id] || 0) + 1;
console.log(JSON.stringify(counter));
}
body div {
display: flex;
flex-direction: row;
grid-column-gap: 1em;
align-content: center;
}
.as-console-wrapper { max-height: 2.667em !important; }
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg(this)" src="http://placekitten.com/120/60" />
</div>
<div class="2">
<img id="test2" onclick="promptImg(this)" src="http://placekitten.com/150/75" />
</div>
<div class="3">
<img id="test3" onclick="promptImg(this)" src="http://placekitten.com/160/80" />
</div>
</div>
Or store the click as a data attribute using dataset.
const counter = { };
const displayClickFrequency = () =>
console.log(JSON.stringify([...document.querySelectorAll('img')]
.reduce((map, img) => ({
...map,
[img.id]: parseInt(img.dataset.clicked, 10) || 0
}), {})));
function promptImg(img) {
const previousValue = parseInt(img.dataset.clicked, 10) || 0;
img.dataset.clicked = previousValue + 1;
displayClickFrequency();
}
body div {
display: flex;
flex-direction: row;
grid-column-gap: 1em;
align-content: center;
}
.as-console-wrapper { max-height: 2.667em !important; }
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg(this)" src="http://placekitten.com/120/60" />
</div>
<div class="2">
<img id="test2" onclick="promptImg(this)" src="http://placekitten.com/150/75" />
</div>
<div class="3">
<img id="test3" onclick="promptImg(this)" src="http://placekitten.com/160/80" />
</div>
</div>
You can do it by using an event listener and checking the id of its target element:
document.addEventListener("click", function(element) {
if (element.target.id === "test1") {
//do something
}
});
You can do that with one of there two options:
function promptImg() {
console.log(event.target);
}
[...document.querySelectorAll(".flowers-with-eventlistener img")].forEach(img => {
img.addEventListener("click", () => {
console.log(event.target)
})
})
img {
width: 100px;
height: 100px;
}
<div class="flowers-with-onclick">
<img onclick="promptImg()" src="rosa-avon-crvena-ajevke-52-373-standard-1.png" >
<img onclick="promptImg()" src="gerbera.jpg">
<img onclick="promptImg()" src="gipsofila.jpg">
</div>
<div class="flowers-with-eventlistener">
<img src="rosa-avon-crvena-ajevke-52-373-standard-1.png" >
<img src="gerbera.jpg">
<img src="gipsofila.jpg">
</div>
If you apply a class to all of the images, you can create an event listener to find out which one has been clicked.
You can test it yourself by using the snippet below and clicking the images. Hope this helped.
var images = document.querySelectorAll(".shared-class");
for (i = 0; i < images.length; i++) {
images[i].addEventListener("click", function() {
console.log(this)
})
}
<div>
<img src="#" id="test1" class="shared-class" />
<img src="#" id="test2" class="shared-class" />
<img src="#" id="test3" class="shared-class" />
</div>
You possibly wat to delegate your clicks to the container - in your case the flowers div
window.addEventListener("load", function() { // on page load
document.getElementById("flowers").addEventListener("click", function(e) { // on click in flowers
const tgt = e.target;
if (tgt.tagName === "IMG") {
console.log(tgt.id);
}
})
})
img { width: 200px; }
<div id="flowers">
<div class="1"> <img id="test1" src="https://pharmarosa.hr/galeria_ecomm/5413/rosa-avon-crvena-ajevke-52-373-standard-1.png" /> </div>
<div class="2"> <img id="test2" src="https://upload.wikimedia.org/wikipedia/commons/2/23/Azimut_Hotels_Red_Gerbera.JPG" /></div>
<div class="3"> <img id="test3" src="https://www.provenwinners.com/sites/provenwinners.com/files/imagecache/low-resolution/ifa_upload/gypsophila-festival-star-02.jpg" /> </div>
</div>
To notice when a user clicks an element (such as an image) on your webpage, you probably want to use the .addEventListener method on that element or one of its "ancestor" elements in the DOM.
Check out MDN's Event Listener page and see the verbose example in the snippet.
// Identifies some elements;
const
flowersContainer = document.getElementById("flowers"),
rosaImg = document.getElementById("rosa-img"),
gerberaImg = document.getElementById("gerbera-img"),
gipsofilaImg = document.getElementById("gipsofila-img"),
countersContainer = document.getElementById("counters");
// Calls `handleImageClicks` when the user clicks on flowersContainer
// (This "event delegation" lets us avoid adding a listener
// for each image, which matters more in larger programs)
flowersContainer.addEventListener("click", handleImageClicks);
// Defines `handleImageClicks`
function handleImageClicks(event){
// Listeners can access events, which have targets
const clickedThing = event.target;
// Calls `incrementCount` for the selected flower
if(clickedThing == rosaImg){ incrementCount("rosa"); }
else if(clickedThing == gerberaImg){ incrementCount("gerbera"); }
else if(clickedThing == gipsofilaImg){ incrementCount("gipsofila"); }
}
// Defines `incrementCount`
function incrementCount(flowerName){
const
// `.getElementsByClassName` returns a list of elements
// (even though there will be only one element in the list)
listOfMatchingElements = countersContainer.getElementsByClassName(flowerName),
myMatchingElement = listOfMatchingElements[0], // First element from list
currentString = myMatchingElement.innerHTML, // HTML values are strings
currentCount = parseInt(currentString), // Converts to number
newCount = currentCount + 1 || 1; // Adds 1 (Defaults to 1)
myMatchingElement.innerHTML = newCount; // Updates HTML
}
#flowers > div { font-size: 1.3em; padding: 10px 0; }
#flowers span{ border: 1px solid grey; }
#counters span{ font-weight: bold; }
<div id="flowers">
<div><span id="rosa-img">Picture of rosa</span></div>
<div><span id="gerbera-img">Picture of gerbera</span></div>
<div><span id="gipsofila-img">Picture of gipsofila</span></div>
</div>
<hr />
<div id=counters>
<div>User clicks on rosa: <span class="rosa"></span></div>
<div>User clicks on gerbera: <span class="gerbera"></span></div>
<div>User clicks on gipsofila: <span class="gipsofila"></span></div>
</div>
In your promptImg function if you use jquery, and you should, inside it add
var idClick=$(this).attr("id");
console.log("This link was clicked"+idClick);
and then you can easily IF it

Animated gif alternative using jQuery to animate an image sequence

I put together this very simple jQuery code to animate a sequence of images. It works perfectly. you can view it here.
But now I am trying to update the code so it could work on multiple image sequences at once as long as it has its own class that is referenced in the jQuery code. So I updated it - view below. Unfortunately my updates are not working. Can you guys help me resolve this issue? Thank you in advance!
let aniOne = $(".animation.first img");
let aniTwo = $(".animation.second img");
let currentImg = 0;
function changeImg(allImg){
$(allImg[currentImg]).fadeOut(0, function(){
if(currentImg == allImg.length -1){
currentImg = 0;
}else {
currentImg++;
}
$(allImg[currentImg]).fadeIn(0)});
}
setInterval(changeImg(aniOne), 0050);
setInterval(changeImg(aniTwo), 0050);
.animation {
width: 30%;
}
.animation img {
display: none;
}
.animation img:first-of-type {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="animation first">
<img src="http://s23.postimage.org/t57meexkb/horse_1.png">
<img src="http://s23.postimage.org/i86apnasr/horse_2.png">
<img src="http://s23.postimage.org/6kc8v3lnv/horse_3.png">
<img src="http://s23.postimage.org/w4ej1j71n/horse_4.png">
<img src="http://s23.postimage.org/ddclrdch7/horse_5.png">
<img src="http://s23.postimage.org/nbxkdulwr/horse_6.png">
<img src="http://s23.postimage.org/phrv8cpd7/horse_7.png">
<img src="http://s23.postimage.org/n1un88wob/horse_8.png">
<img src="http://s23.postimage.org/9yz0oz6gb/horse_9.png">
<img src="http://s23.postimage.org/6gn0sl5kb/horse_10.png">
<img src="http://s23.postimage.org/vnxwsu8ob/horse_11.png">
<img src="http://s23.postimage.org/bhuetyd0r/horse_12.png">
<img src="http://s23.postimage.org/imc82zka3/horse_13.png">
<img src="http://s23.postimage.org/auvi4fg4r/horse_14.png">
</div>
<div class="animation second">
<img src="https://i.imgur.com/5QGZklx.png">
<img src="https://i.imgur.com/5QGZklx.png">
<img src="https://i.imgur.com/i1oLaES.png">
</div>
As Chris G stated above:
The working code uses setInterval(changeImg, 50) which will work fine. The problem with your current attempt is setInterval(changeImg(aniOne), 50) which evaluates to a call to changeImg(aniOne), then a call to setInterval(undefined, 50) (since changeImg doesn't return anything). If you want this to work, you need to make changeImg into a function that returns a function. – Chris G
After we add these problems, we then have the issue of both animations sharing the currentImg variable, so instead I made two different variables and passed them along with the images. You can handle this many different ways.
let aniOne = $(".animation.first img");
let aniTwo = $(".animation.second img");
let num1 = 0;
let num2 = 0;
function changeImg(allImg, num){
function main(){
$(allImg[num]).fadeOut(0, function(){
if(num == allImg.length -1){
num = 0;
}else {
num++;
}
$(allImg[num]).fadeIn(0)});
}
return main;
}
setInterval(changeImg(aniOne, num1), 0050);
setInterval(changeImg(aniTwo, num2), 0050);
.animation {
width: 30%;
}
.animation img {
display: none;
}
.animation img:first-of-type {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="animation first">
<img src="http://s23.postimage.org/t57meexkb/horse_1.png">
<img src="http://s23.postimage.org/i86apnasr/horse_2.png">
<img src="http://s23.postimage.org/6kc8v3lnv/horse_3.png">
<img src="http://s23.postimage.org/w4ej1j71n/horse_4.png">
<img src="http://s23.postimage.org/ddclrdch7/horse_5.png">
<img src="http://s23.postimage.org/nbxkdulwr/horse_6.png">
<img src="http://s23.postimage.org/phrv8cpd7/horse_7.png">
<img src="http://s23.postimage.org/n1un88wob/horse_8.png">
<img src="http://s23.postimage.org/9yz0oz6gb/horse_9.png">
<img src="http://s23.postimage.org/6gn0sl5kb/horse_10.png">
<img src="http://s23.postimage.org/vnxwsu8ob/horse_11.png">
<img src="http://s23.postimage.org/bhuetyd0r/horse_12.png">
<img src="http://s23.postimage.org/imc82zka3/horse_13.png">
<img src="http://s23.postimage.org/auvi4fg4r/horse_14.png">
</div>
<div class="animation second">
<img src="https://i.imgur.com/5QGZklx.png">
<img src="https://i.imgur.com/5QGZklx.png">
<img src="https://i.imgur.com/i1oLaES.png">
</div>

How to change images on hover on and on with jQuery?

I've got such a problem:
inside my <div></div> there are always 5 images, only 1 is visible other 4 are hidden.
<style>
#id2, #id3, #id4, #id5 { display: none; }
</style>
<div>
<img id="id1" src='image.jpg'>
<img id="id2" src='image.jpg'>
<img id="id3" src='image.jpg'>
<img id="id4" src='image.jpg'>
<img id="id5" src='image.jpg'>
</div>
My aim is to change them in the constant time stamp (for example 1 second) on hover.
$('document').ready(function(){
$('#1').hover(function(){
// #id1 hide
// #id2 show
// #id2 hide
// #id3 show
// #id3 hide
// #id4 show
// #id4 hide
// #id5 show
// #id5 hide
// #id1 show
// and so on...
});
});
It's going to be used as a video preview, divs and inner images are going to be generated from MySQL DB.
Any help appreciated.
Here's a working example, based on what I understood from your question:
$('.preview').hover(function() {
var $that = $(this),
toggleFunction = function() {
var $visibleImg = $('img:visible', $that),
$nextImg = $visibleImg.next('img');
if(!$nextImg.length) {
$nextImg = $('img:first-child', $visibleImg.parent());
}
$nextImg.show().siblings().hide();
};
$that.data('interval', window.setInterval(toggleFunction, 1000));
toggleFunction();
}, function() {
window.clearInterval($(this).data('interval'));
});
.preview img {
display: none;
}
.preview img:first-child {
display: block;
}
.preview {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="preview">
<img src="https://s24.postimg.org/r74b0vcu9/frame_0.gif" />
<img src="https://s24.postimg.org/a7vclm1mp/frame_15.gif" />
<img src="https://s24.postimg.org/600kcv075/frame_30.gif" />
<img src="https://s24.postimg.org/7t82exarl/frame_45.gif" />
<img src="https://s24.postimg.org/5d6912sox/frame_60.gif" />
</div>

HTML Javascript Slideshow Optimization

I had to write my own code of a couple of lines for displaying slideshow on my websites splashpage. I couldnt use any plugin as I had designed the website on HTML5 and css3 and images were synchronized to resize with the browser. Now, coming to the actual problem, the last image takes double time as taken by
each image in the list. Below is the HTML and the javascript pasted.
HTML
<div id="backgrounds">
<div class="bgs" style="z-index:1000;">
<!--<p style="z-index:999; margin:0; margin-top:300px; color:red; position:absolute;">Let the Feeling Wrap Around</p>-->
<img src="images/main_nop.jpg" alt="" class="background" />
</div>
<div class="bgs" style="z-index:999; display: none">
<!--<p style="z-index:999; margin:0; margin-top:300px; color:red; position:absolute;">Let the Feeling Wrap Around</p>-->
<img src="images/main_jkl.jpg" alt="" class="background" />
</div>
<div class="bgs" style="z-index:998; display: none">
<!--<p style="z-index:999; margin:0; margin-top:300px; color:red; position:absolute;">Let the Feeling Wrap Around</p>-->
<img src="images/main_ghi.jpg" alt="" class="background" />
</div>
<div class="bgs" style="z-index:997; display: none">
<!--<p style="z-index:999; margin:0; margin-top:300px; color:red; position:absolute;">Let the Feeling Wrap Around</p>-->
<img src="images/main_def.jpg" alt="" class="background" />
</div>
<div class="bgs" style="z-index:996; display: none">
<!--<p style="z-index:999; margin:0; margin-top:300px; color:red; position:absolute;">Let the Feeling Wrap Around</p>-->
<img src="images/main_abc.jpg" alt="" class="background" />
</div>
</div>
JAVASCRIPT
var count = 0;
var repeatCount = 0;
var backgrounds = $('.bgs').length;
function startSlideShow() {
myRecFunc = setInterval(function () {
if (count == backgrounds) {
$('.bgs').eq(0).stop(true, true).hide(1000, 'easeOutExpo');
$('.bgs').eq(backgrounds - 1).show(1000, 'easeOutExpo');
}
if (count < backgrounds) {
$('.bgs').eq(count).stop(true, true).show(1000, 'easeOutExpo');
$('.bgs').eq(count - 1).stop(true, true).hide(1000, 'easeOutExpo');
count++;
}
else {
count = 0;
repeatCount++;
}
}, 1000);
}
startSlideShow();
The first if() in the code above is the one I added to handle the situation I stated on top, thanks in advance for the help.
You have a condition where you do nothing for a whole interval which is your "else" case. Try moving that check inside so that it happens immediately.
var count = 0;
var repeatCount = 0;
var backgrounds = $('.bgs').length;
function startSlideShow() {
myRecFunc = setInterval(function () {
$('.bgs').eq(count).stop(true, true).show(1000, 'easeOutExpo');
$('.bgs').eq(count - 1).stop(true, true).hide(1000, 'easeOutExpo');
count++;
if (count === backgrounds) {
count = 0;
repeatCount++;
}
}, 1000);
}
startSlideShow();​

Categories

Resources