Getting data from LocalHost - javascript

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();

Related

JS: Select any avatar from a folder

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=""/ >

how to change several images with a single click

Im really new to javascript, and while Im learning, Im trying to change images in a gallery to others with an onclick function.
I have links to different galleries. When I click on link 1, the imgs are one1.jpg, one2.jpg and so on. When I click on link 2, imgs are two1.jpg, two2.jpg, etc.
This is the rough script I made for Link 1:
<script>
function one() {
document.getElementById("foto1").src="one1.jpg";
document.getElementById("foto2").src="one2.jpg";
}
</script>
Link 1
Link 2
<img id="foto1" src="tre1.jpg"></a>
<img id="foto2" src="tre2.jpg"></a>
etc.
I made another function called two() for the second link with same content but changing src to what I want. And for every link I add, I copy the script and change it a little.
I know there is a way to optimize to a single script with variables or something .
Any help?
Thanks
In order to differentiate group of images there must be a pattern.
try to add a class on each img tag to differentiate images for changing their source, and the you can loop through images as follows:
Link 1
Link 2
<img class="img1" id="foto1" src="foto1.jpg">
<img class="img1" id="foto2" src="foto1.jpg">
<img class="img2" id="foto3" src="pic1.jpg">
<img class="img2" id="foto4" src="pic2.jpg">
<script>
function one() {
var img = document.getElementsByClassName("img1");
for (var i in img) {
img[i].src = "foto" + 1 + ".jpg"
}
}
function two() {
var img = document.getElementsByClassName("img2");
for (var i in img) {
img[i].src = "pic" + 1 + ".jpg"
}
}
</script>

Updating Json Data for angular-flexslider breaks on 'removeSlide'

Problem: My json object is updating, but the slider does not update for all resorts. It should be updating as the json object changes but sometimes does not.
For the resorts (image collections) that do not update, it gives me an error: "cannot read property 'element' of undefined and breaks on angular-flexslider.js line 104. I cannot find any relation with the resorts that are giving me this error vs the ones that do not.
Summary of my script: I'm using angular-flexslider with a slider sync. I have a service that grabs image data and sends it to the controller. The controller picks it up and runs reorganize(), which takes the object it is given and reformats it into an array that flexslider supports.
This object needs to be updated as the images are updated. I have a dropdown that allows users to change the resort and I want the slider to reflect those changes.
Here is my code
JS:
resortModule.controller('galleryController', ['$scope', 'locaService', function($scope, locaService) {
//object to receive images
$scope.images;
//object used for image slider
$scope.imagePaths = [];
//variable that gives me resort ID
$scope.resort;
//restructures images array to work better with image slider
$scope.reorganize= function(){
$scope.imagePaths.length= 0;
for(var i = 0; i < $scope.images.length; i++) {
var obj= {custom: "assets/images/resorts/" + $scope.images[i].resort + "/gallery/" + $scope.images[i].file_name, thumbnail:"assets/images/resorts/" + $scope.images[i].resort + "/thumbnail/" + $scope.images[i].file_name}
$scope.imagePaths.push(obj);
}
}
//watches factory for updates to objects/ variables
$scope.$on('imagesUpdated', function() {
$scope.images = locaService.images;
$scope.reorganize();
});
$scope.$on('resortUpdated', function() {
$scope.resort = locaService.resort;
});
}]);
HTML:
<flex-slider slider-id="slider" flex-slide="image in imagePaths track by $index" animation="fade" animation-loop="false" sync="#carousel" slideshow="false" control-nav="false" prev-text="" next-text="" init-delay="100">
<li>
<img ng-src="{{image.custom}}" alt="Luxury Resort Rental Image">
</li>
</flex-slider>
<flex-slider class="slides hide-tablet-down" slider-id="carousel" flex-slide="image in imagePaths track by $index" animation="slide" animation-loop="false" item-width="210" item-margin="5" as-nav-for="#slider" slideshow="false" prev-text="" next-text="" control-nav="false">
<li>
<img ng-src="{{image.thumbnail}}" alt="Luxury Resort Rental Image">
</li>
</flex-slider>
Does anyone have any insight on this error? Or what I might be doing wrong? I've been researching it all day but have only found this:
https://github.com/thenikso/angular-flexslider/issues/53
and this:
https://github.com/thenikso/angular-flexslider/pull/63
Which did nothing for me, but I might not have understood them entirely. I'm not a seasoned angular developer and I'm learning as I go along. Thanks in advance for your help.
I commented out the following lines in the angular-flexslider.js and it seemed to fix the problem. Let me know if you have a better solution:
if ((toAdd.length === 1 && toRemove.length === 0) || toAdd.length === 0) {
...
return $scope.$evalAsync(function() { return slider.addSlide(item.element, idx); }); }); } return; }`

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;

change target of javascript to div

I have some img tags with id's but through validating my code I realized that the tags were missing a src. The only problem is, is that in my javascript these img id's are targeted and when I changed them to a div instead the images disappeared.
Basically this page is staff profiles with images and content, the user clicks an arrow and it goes to the next profile. How the code works is that the images are in an external javascript file and when I click something on page and inspect the html I saw that the image appears within the image tags in HTML.This javascript was given to me so I am not sure what to change, I don't know much about javascript. Let me know if any clarification or code is needed, this is very difficult to explain as I don't understand what is going on.
HTML -the problem
<img id='staff_image' class='staff_image'></img>
<img id='staff_name' class='staff_name'></img>
HTML -the page
<div id='staff_slider' class='slider'>
<div class='staff_container'>
<img id='staff_image' class='staff_image' src"#" alt="image"
</div>
<img id='staff_name' class='staff_name' src"#" alt="image"></div>
<div id='staff_details' class='staff_details'></div>
</div>
<div class='slider_navigation'>
<img class='navLeft' src='../assets/images/staff_profile/slider/navLeft.png' alt= "nav left" onclick='navigate(-1);'/>
<img class='navRight' src='../assets/images/staff_profile/slider/navRight.png' alt="nav right" onclick='navigate(1);'/>
</div>
</div>
<script src="staff_profiles.js"></script>
<script src="slider.js"></script>
<script>
navigate(0);
</script>
JAVASCRIPT- slider.js (this is for two arrow buttons that scroll through the profiles)
var slider_index = 0;
function navigate(direction){
slider_index += direction;
if(slider_index < 0)
{
slider_index = profiles.length - 1;
}
else if(slider_index == profiles.length)
{
slider_index = 0;
}
loadProfile(profiles[slider_index]);
}
function loadProfile(profile)
{
var staff_image = document.getElementById('staff_image');
staff_image.src = imgPath + profile.img;
var staff_name = document.getElementById('staff_name');
staff_name.src = titlePath + profile.title;
var staff_details = document.getElementById('staff_details');
staff_details.innerHTML = profile.details;
}
JAVASCRIPT - staff_profiles.js (seperate file, these are the links to the images needed for the profiles, the content are in strings)
var imgPath = "../assets/images/staff_profile/staff/";
var titlePath = "../assets/images/staff_profile/titles/";
var profiles =
[
//
{
img:"fin.jpg",
title:"fin.png",
details:"<p>Stunt pilot with the Red Arrows (UK airforce stunt team), has served in combat choppers in 3 recent wars, and fears nothing except small dogs and single women.</p>" +
"<p>Owns an Extra EA-200 for the ultimate full stunt flight experience, and flies all our other fixed wing craft much more sedately when required. And, yes, that is his real name. He's Irish and he doesn't want to talk about it.</p>"
},
//
{
img:"hans.jpg",
title:"hans.png",
details:"<p>Hans has flown almost everything there is to fly. Hanshas has flown almost everything there is to fly. He first took the controls of a small plane at 12 years old, and flew solo when he was 14. After a few years flying anything anywhere he settled into a series of test pilot jobs but left that because he prefers company when hes in the air.</p>"
},
//
{
img:"john.jpg",
title:"john.png",
details:"<p>With over 10,000 hours piloting helicopters in the bush and mountains of the Southern Alps for deer recovery and mountain rescue operations, Doc is well qualified to land you and your friends in remote parts of the country that only he knows about. He ll help you plot your route, drop extra provisions where you want them, and pick you up when your done.</p>"
},
{
img:"wendy.jpg",
title:"wendy.png",
details:"<p>13 years commercial pilot in Africa, Russia and South America, during which she survived 3 crashes (none her own fault, she maintains). Owns a Cessna-172Skyhawk P that is ideal for low level sight seeing, rides a Harley and is a ski instructor during the seas</p>"
}
];
You need to change the following lines in the loadProfile function
var staff_image = document.getElementById('staff_image');
var myimg = staff_image.getElementsByTagName('img')[0];
myimg.src = imgPath + profile.img;
The HTML could be like this
<div id='staff_image'>
<img src"#" alt="image"/>
</div>
Hope it's useful to you

Categories

Resources