JS: Select any avatar from a folder - javascript

So I'm working on some project and in some part of the website, I do need to show random avatar images from a specific folder, each X seconds (I'm using setInterval for this).
BUT the problem is that I can't select random images.
So basically this is a part of my code:
setInterval(function() {
$('#avatar').attr('src', 'assets/img/avatars/*.jpg');
}, 1500);
As you can see, I've tried that *.jpg but it doesn't work.
Do you have any other ideas?
Thank you!

As Rory McCrossan suggested, You can create an array which will contains all the avatar images.
After that in your setInterval function you use the Math.Random to generate a random integer from the given array length and based on that fetch the avatar and show it.
var avatars = [
"img/pic1.jpg",
"img/pic2.jpg",
"img/pic3.jpg",
"img/pic4.jpg",
"img/pic5.jpg"
];
setInterval(function(){
var random = Math.floor(Math.random() * avatars.length);
var item = avatars[random];
$('#avatar').attr('src', item);
$('#avatar').attr('alt', item);
},2000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="avatar" alt=""/ >

Related

how to counter pagination show in slider

I used the slider where i got bug occur. I wanted to show counter pagination on slider but i was unable to do this. In form of Current Number of Page/ Total number of pages like 1/4,2/4 and so on.
https://codepen.io/anon/pen/WJRqQj
<div id="credit"><br>Slide No.<span id="count">1/4</span><br></div>
You can modify the left and right buttons click functions. Also do not forget to update the automatic slider accordingly. I'm also sure you can get the total index somewhere within so that you don't have to hardcode the "/4" part. Update the below functions:
var leftArrow = $('<div>', {'class': 'jislider__left-arrow'}).click(function () {
animate.control(--animate.index);
document.getElementById("count").textContent = animate.index+"/3";
});
var rightArrow = $('<div>', {'class': 'jislider__right-arrow'}).click(function () {
animate.control(++animate.index);
document.getElementById("count").textContent = animate.index+"/3"
});
This will not be enough, you probably should not hardcode the denominator "/4" part as well. I do not know the library you use, but I guess this is sufficient to give you the overall number of "unique" divs with different source:
var x = Array.prototype.slice.call(document.querySelectorAll(".jislider__img"))
.map(function(d,i){return {node:d,url:getComputedStyle(d).backgroundImage}})
.reduce(function(ac,d,i,a){
!ac.some(function(dd,ii){return dd.url === d.url})
? ac.push(d)
: void(0);
return ac
},[]).map(function(d,i){
return d.node;
})
x.length is 3 in your case. So although you have 5 divs, you have 3 images. You can also see it in the dots below (3 dots are there in your carousel). For the left and right arrow functions above, calculate var l = x.length before hand, and then you can do:
document.getElementById("count").textContent = animate.index+"/" + l;
so you don't have to hardcode it. I had to modify your slider a bit, a working fiddle:
https://jsfiddle.net/ibowankenobi/szwr20ec/5/

Getting data from LocalHost

Let's say I have many school images on my localhost PC with images have names of the Campus_id of the school. But every school may have 1 or many images. Let's say that a school with id=20 has images like 20_1, 20_2, 20_3 ... and school with id=23, h an s image like 23_1 only. I want to get those images and show it using Angular and Html. What i did is to put the images in an array and show it using Ngfor. But the problem is that i do not know the number of the images in each school.
Here is how to iterate over all photos saved in data.attributes.photos, and generate a separate slide for each one.
Environment URL:
resimUrl: 'http://localhost/mebresim/'
data.attributes.photos = environment.resimUrl + data.attributes.kampus_id + '.jpg';
OR simply its like:
TypeScript:
data.attributes.photos = [ "12.jpg", "12_1.jpg", "12_2.jpg" ]
HTML:
<ngb-carousel>
<ng-template ngbSlide *ngFor="let photo of navbar.infoData.attributes.photos">
<img class="card-img-top img-fluid w-full" [src]="photo" alt="Okul Fotoğrafı Bulunamadı">
</ng-template>
</ngb-carousel>
Here getting and putting in array is working if you know that each school has constant number of images. But how about if i do not know the number of images a school has?
You can try loading the images in the numerical order and continue when it fails.
//This function will try to load an image and fire callbacks on the availablity.
//Images are automatically cached at this point (bonus)
function testImage(url) {
var tester=new Image();
tester.onload=imageFound;
tester.onerror=imageNotFound;
tester.src=url;
}
function imageFound() {
loadNext(); //Try the next one
}
function imageNotFound() {
//Last image loading failed. Proceed showing images you have got.
console.log('Last Index: ' + lastIndex - 1;);
//showImages();
}
function loadNext(){
testImage('http://localhost/mebresim/' + data.attributes.kampus_id + '_' + lastIndex);
lastIndex++;
}
//Trigger image loading
var lastIndex = 0;
loadNext();

How to create a persistent random countdown?

Basically, I need a counter that will go backwards from 100-1 slowly as users enter our website. We are only giving out "100" free coupon but want to give the appearance that users are quickly grabbing them in order to create urgency and have the prospect give us their email. I am using Unbounce to host our mobile landing page.
I came across a similar post to mine but the code generated numbers randomly in the millions. Here is the link for further help: https://stackoverflow.com/a/17964971
Quick example:
Be the first to know when we launch! We are only giving out 100 coupons and there are only (x) amount left.
Click here to get yours!
Count down at a random rate between 5 seconds and 1 second, save the current to the browser so if the user revisits the page the number doesn't reset
(Demo)
var i = 100;
var counter = document.getElementById('counter');
if(localStorage.counter) {
i = localStorage.counter;
}
function countDown() {
if(i > 0) {
i--;
console.log(i);
counter.innerText = i;
localStorage.counter = i;
var timeout = Math.floor(Math.random() * (5000 - 1000)) + 1000;
setTimeout(function(){
countDown();
}, timeout);
} else {
document.getElementById('counter-wrp').innerText = 'Oh no, you missed out! All of the coupons are gone.'
}
}
countDown();
<span id="counter-wrp">Be the first to know when we launch! We are only giving
out 100 coupons and there are only <span id="counter" style="color: red;"></span> left</span>
I create this jsFiddle for you using your example
My method utilizes localStorage, which is perfect for this type of function. You can read more about local storage here w3schools. You need to this save the count.
You will notice that to initialize the counter you need additional options
var counter = new Counter({
start: 123456789,
up: '#btnUp',
down: '#btnDn',
storageKey: 'count'
});
up: and down: are just jQuery selectors for the buttons I added with id's btnUp and btnDn. storagekey: can be whatever string you'd like to set to retrieve our count out of localstorage.
here are my buttons
<div class="buttons">
<button id="btnUp" type="button">+</button>
<button id="btnDn" type="button">-</button>
</div>
I hope this helps

Image gallery thumbnails

I'm new to Java and need to build an image gallery.
I have a catalogue of images: each category has a thumbnail; each category has three images.
Process:
Click on thumbnail, bigPic changes its src to show the image you clicked on.
Three dots below bigPic can be clicked to see the other images in that category (so if another thumbnail is chosen, the srcs they pass onto bigPic will change too)
I have tried a few things and looked around but I cannot seem to make it work.
Here is what I have so far:
<script>
function backColor(a) {
document.getElementById("bigPic").src = a;
}
function varE(e){
var chosen = e;
document.getElementsByName("firstDot").id = chosen;
}
function setM(m) {
var chosenImage = m.id;
document.getElementById("bigPic").src = chosenImage;
}
</script>
bigPic:
<img class="bigPic" id="bigPic">
thumbnail image:
<img class="thumb" src="categoryImageSRC" onclick="backColor('anotherImageSRC'); varE('otherImageSRC')">
dot/circle that shows another image in category:
<img name="firstDot" id="" src="dotImageSRC" onclick="setM(this)">
Any ideas on how to go about this, examples and corrections are very welcome! Thank you!
get element by name returns an array of element so you need to change this line in varE function
document.getElementsByName("firstDot").id = chosen;
to
document.getElementsByName("firstDot")[0].id = chosen;

Can't get sessionStorage to work correctly

I have multiple buttons that when they are clicked an image is loaded and the image is supposed to stay there based even when the page refreshes. When I use this the button with the highest setItem value always shows even if I click on other button. How do I fix this?
here is one of the scripts:
<script type="text/javascript">
var isImage1 = sessionStorage.getItem('2');
function showImage1() {
sessionStorage.setItem('isImage1', '2');
$("#loadingImage1").show();
$("#loadingImage").hide();
$("#loadingImage2").hide();
$("#loadingImage3").hide();
$("#loadingImage4").hide();
$("#loadingImage5").hide();
$("#loadingImage6").hide();
}
if(isImage1 == 2) showImage1();
</script>
and here is one of my buttons:
<input name="EPL/MECH DESIGN - TECHS" style="white-space:normal"
onclick="moveText(this.name);showImage1();form1.submit()"
style="width: 275px" type="button" value="7SBD EPL/Mech. Design Techs" />
Update: I have updated this line
var isImage1 = sessionStorage.getItem('2');
to
var isImage1 = sessionStorage.getItem('isIamge1');
but my issue still exists, that the isImage with the largest value stays even when i click the other buttons, so help is still needed.
In your session storage, you are setting the value of the 'isImage1' Item to '2'
sessionStorage.setItem('isImage1', '2');
But in your code to retrieve the value you are actually retrieving the item '2'
var isImage1 = sessionStorage.getItem('2');
You need to change your sessionStorage.getItem to reference 'isImage1'
var isImage1 = sessionStorage.getItem('isImage1');
Then you should get the value you are expecting.
There are loads of good jsfiddles on session storage. you may get some ideas from this one:
http://jsfiddle.net/gabrieleromanato/XLRAH/
Incidently; this is a very small value you are storing, why not store it in a cookie instead?
EDIT:
based on the fact that you have multiple functions exactly like this one, you are better off following Ken's solution, the only thing I would add is a wildcard to turn off the other images:
function showImage(imgNum) {
sessionStorage.setItem('Image',imgNum);
$("[id^=loadingImage]").hide();
$("#loadingImage" + imgNum).show();
}
showImage(sessionStorage.getItem('Image'));
The code in the buttons would then be showImage(1) instead of showImage1();
_Pez
By re-factoring the code a little you can do something like this:
/// setup some vars including max number of images
var maxImages = 6, i = 1, v;
/// now loop through and get the items for each image
for(; i =< maxImages; i++) {
v = sessionStorage.getItem('isImage' + i);
/// if in storage, call show image with the number to show
if (v !== null) showImage(i);
}
/// show image based on number
function showImage(num) {
sessionStorage.setItem('isImage' + num, '1');
$("#loadingImage" + num).show();
}
Also note that sessionStorage only deals with strings. So in order to check a specific number you need to convert it to one first parseInt(value, 10);.
But in this case the 1 that we set can be anything - it's just to store some value so sessionStorage doesn't return null.
In the button code you can change it to do this:
<input name="EPL/MECH DESIGN - TECHS" style="white-space:normal"
onclick="moveText(this.name);showImage(1);form1.submit()"
style="width: 275px" type="button" value="7SBD EPL/Mech. Design Techs" />

Categories

Resources