I am trying to set an image dynamically at runtime using javascript. However i always get 404 error in firebug saying image could not be found. when i run this the javascript seems to look for the image in the Home Folder rather than the image folder. Am i missing a format to specify the image urls?
Why is it looking at that location whereas it should be looking at Images folder in the solution?
Also if i make that javascript external the html cannot access it even though my references to the js file are correct.
Anyone willing to contribute on this? you help be very much appreciated.
Here is my code
Html
<body onload="startTime();">
<div class="img">
<img id="img1" border="0" src="~/Images/Ghandrukpic4.jpg" alt="GhanddrukPic4" class="image" />
</div>
</body>
Javascript Code
$(function () {
function startTime() {
var imgArray = new Array("Images/60987Ghandruk Village.jpg", "Images/GhandrukPic2.jpg", "Images/ghandrukpic3.jpg");
var imgCount = 0;
if (imgCount == imgArray.length) {
imgCount = 0;
}
document.getElementById("img1").src = imgArray[imgCount];
imgCount++;
setTimeout("startTime()", 5000);
}
});
add a / in front of your Images string in the array.
new Array("/Images/60987Ghandruk Village.jpg", "/Images/GhandrukPic2.jpg", "/Images/ghandrukpic3.jpg");
This will let the browser know to request from the root directory of your site. If there is no forward slash it is a Relative path to the page that is loaded. So if the page you are on is http://yoursite.com/home/ then it will be looking in the images directory nested in your nonexistant /home directory.
As far as your javascript. Unwrap your startTime function like so in your external and it should work fine.
function startTime() {
var imgArray = new Array("/Images/60987Ghandruk Village.jpg", "/Images/GhandrukPic2.jpg", "/Images/ghandrukpic3.jpg");
var imgCount = 0;
if (imgCount == imgArray.length) {
imgCount = 0;
}
document.getElementById("img1").src = imgArray[imgCount];
imgCount++;
setTimeout("startTime()", 5000);
}
Related
Good day! So I have been practising web development again and found Laravel to be fun to learn (and I'm enjoying it a lot) and I have decided to recreate my portfolio website with it to practice it.
So the problem is this:
I am trying to display a list of images from a folder called designImages and this will be updated every time I have a good UI design. so it makes sense to make it dynamically ready so I do not have to manually add <img> tags for every image and make my process a lot longer. I plan to just make a js file that will only be adjusted once depending on how many images are currently in the folder.
But the problem is when I display the images on my blade page, it shows the broken image icon
view it here
EDIT: When I try to inspect element, the image is not displaying and instead, shows 404 error. mywebsite.test/designImages/design-1 for example.
The code on my js file is this
const imageContainer = document.querySelector(".imageContainer");
for (let i = 1; i < 14; i++) {
const img = document.createElement("img");
img.src = "{{ asset('designImages/design-${i}.png') }}";
imageContainer.append(img);
}
and the code for the master file (app.blade.php) for my index.blade.php is:
<body>
#yield('content-5')
#stack('head')
</body>
and the index.blade.php code is this:
#section('content-5')
<div class="imageContainer">
<!-- images will come here -->
</div>
#endsection
#push('head')
<script src="{{ asset('js/imageGrid.js')}}"></script>
#endpush
Any help or tips will be greatly appreciated :)
-----EDIT-----
Fixed it! :) the updated javascript code is this:
const templateURL = "storage/designImages/design-?.png";
const imageContainer = document.querySelector(".imageContainer");
for (let i = 1; i < 14; i++) {
const img = document.createElement("img");
img.src = templateURL.replace("?", i);
imageContainer.append(img);
}
fixed it using this code:
const templateURL = "storage/designImages/design-?.png";
const imageContainer = document.querySelector(".imageContainer");
for (let i = 1; i < 14; i++) {
const img = document.createElement("img");
img.src = templateURL.replace("?", i);
imageContainer.append(img);
}
So I'm fiddling with a fun idea for an offline website I'm currently trying to develop.
It'll be offline as it's meant to be practice for later study assignments and such.
My problem is the following: I have a javascript function that replaces a PNG with a GIF and after the animation it should redirect the person to another html I've made.
The source for the JS animation is mainly acquired from here already, but I cannot seem to make it work in the ways I originally intended.
The way it currently works is that I click the png and it'll turn into a gif (no problem there) but what I want is that it runs my js script and then redirect to another .html file (url).
The following is my HTML:
<object id="syringe">
<img src="img/syringe.png" height="750" alt="img/syringe.gif" class="center">
<h2>Click the syringe to inject yourself with a daily dose of puns and jokes</h2>
</object>
The following is the JS:
(function($) {
var getGif = function() {
var gif = [];
$('img').each(function() {
var data = $(this).data('alt');
gif.push(data);
});
return gif;
}
var gif = getGif();
var image = [];
$.each(gif, function(index) {
image[index] = new Image();
image[index].src = gif[index];
});
$('#syringe').on('click', function() {
var $this = $(this),
$index = $this.index(),
$img = $this.children('img'),
$imgSrc = $img.attr('src'),
$imgAlt = $img.attr('data-alt'),
$imgExt = $imgAlt.split('.');
if($imgExt[1] === 'gif') {
$img.attr('src', $img.data('alt')).attr('data-alt', $imgSrc);
} else {
$img.attr('src', $imgAlt).attr('data-alt', $img.data('alt'));
}
$this.toggleClass('play');
});
})(jQuery);
It is to my understanding that I can add a delay and then another function to something in the js - such as the following, which is what I intend to do, however cannot accomplish.
[FUNCTION HERE],1000,
function(){
window.location.href=myredirectionuri;
});
And that is my problem.
It looks like you want to have the gif display for a second or two and then redirect, right? If $this.toggleClass('play'); is the end, then just insert this right after it:
setTimeout(() => window.location.href = myredirectionuri, 1000);
That'll wait for 1000ms and then redirect to the new page.
In the animation script, after it changes to a gif, insert
setTimeout(function() {
/* redirect code */
}, /* length of gif in milliseconds */ )
I have a div that contains a number of Instagram images, produced by the instafeed.js plugin. After running the plugin, the resultant HTML looks like this:
<div id="instafeed">
<a><img /></a>
<a><img /></a>
<a><img /></a>
etc...
</div>
I am trying to find a way to load the contents of this div into an array; I believe that the easiest way would be to just take the tags, which is fine.
I'm pretty inexperienced with both JS and jQuery, which is why I'm having difficulty achieving this and I've not been able to find any forum posts that quite do what I'm hoping to achieve.
So far, all I'm trying to do is load the contents of the div into an array and print it back out to the document, which should (in my mind anyway) add the tags back into the HTML. I'm trying with both JavaScript and jQuery and having little success with either. I'd appreciate any thoughts:
JS:
var containerDiv = document.getElementById('instafeed');
var pics = containerDiv.getElementsByTagName('img');
console.log(pics); //Tells me at least that I have an array of img
for (var i = 0; i < pics.length; i++) {
document.write(pics[i]);
} //Seemingly does nothing
jQuery:
(I'm really sorry if this code is just all wrong, I really don't know jQuery very well at all)
$(document).ready(function() {
var pics = [];
$('#instafeed').find('img').each(function() {
pics.push($(this));
});
for (i = 0; i < pics.length; i++) {
console.log(pics[i]);
}
});
Any thoughts, tips or pointers would be much appreciated.
Edit:
Just to add a little background to my problem, to avoid causing any more confusion.
I'm trying to pull four random images from a user-specific Instagram feed for display on a website. instafeed.js can pull just four images and it can randomise the images, but Instagram itself always sends the four most recent images, so the plugin is just randomising the order of the same four pictures each time.
I'm trying to let the plugin send through every picture, which will go into the div instafeed. From here I want to load all of the contained images into an array so that I can randomly pick four images for display on the site.
JQuery code that you write is correct. Only you need the div where you need to put the images.
$(document).ready(function() {
var pics = [];
$('#instafeed').find('img').each(function() {
pics.push($(this));
});
for (i = 0; i < pics.length; i++) {
$('div#yourDiv').append(pics[i]);
}
});
See the line of the for()
You can extract only the SRC of the images and then make like you want
$('#instafeed').find('img').each(function() {
pics.push($(this).attr('src'));
});
console.log(pics); // returns an array of src.
Thank you to everyone who has tried to help me along with this. It turns out that the problem I was having stemmed from my query attempting to run before instafeed.js had been able to pull the images through from Instagram, and so there was nothing for it to find in the div. I've managed to fix this with a setTimeout.
For anyone who is interested, and just in case anyone else might come across this in future with a similar problem, here is my complete code (it's a little inelegant I'm sure, but I'm still a relative novice at JS.)
function snagImages() {
var pics = [];
$('div#instafeed').find('img').each(function() {
pics.push($(this).attr('src'));
});
reduceGallery(4, pics);
}
function reduceGallery(limit, pics) {
if (limit === undefined) {
limit = 4;
}
var gallery = [];
while (gallery.length < limit) {
var j = Math.floor(Math.random() * pics.length);
if ( gallery.indexOf(pics[j]) > -1) {
continue;
}
gallery.push(pics[j]);
}
displayPics(gallery);
}
function displayPics(gallery) {
for (var i = 0; i < gallery.length; i++) {
document.getElementById('gallery').innerHTML += '' + '<img src="' + gallery[i] + '" alt="Gallery Image" />' + '';
}
}
var userFeed = new Instafeed( {
options
});
userFeed.run();
setTimeout(function() { snagImages() }, 500);
This javascript code is supposed to switch when clicked an image to images from a folder within the html file folder.
After it gets to the last image, if you click again it resets to the first image.
Also there's a fade in and out effect on the appearing images.
It doesn't work and I suspect I wrote the path files to the images wrong somehow and the .attr doesn't change the src of the first image to the others.
Things to keep in mind = an extremely beginner programmer, just picked up html and css in about 2 days, I would appreciate any kind of help!
This is the code:
$(document).ready(function() {
var imageName = ["head.jpg", "head3.jpg", "head4.jpg"];
var indexNum = 0;
$("#head1").click(function() {
$("#head1").fadeOut(300, function() {
$("#head1").attr("src", imageName[indexNum])";
//$(indexNum).css("height=600px,width=1000px")
indexNum++;
if (indexNum > 2) {
indexNum = 0;
}
$("#head1").fadeIn(500);
)};
)};
)};
You got a couple of errors in your code,
You swapped the closing ")" and "}" in the last two lines and you have a random " in the code.
Here's a working example:
$(document).ready(function() {
var imageName = ["http://placehold.it/200x200", "http://placehold.it/300x300", "http://placehold.it/400x400"];
var indexNum = 0;
$("#head1").click(function() {
indexNum = (indexNum + 1) % imageName.length; // this will count 0,1,2,0,1,2,0,1,2... always looping through your images
$(this).fadeOut(function() { //in this context, this refers to the #head, reading it from the DOM over and over again isn't efficient
$(this).attr("src", imageName[indexNum]);
}).fadeIn();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="head1" src="http://placehold.it/200x200" alt="">
Just a small note: Your script (and mine) don't take into account loading times, this means that it will probably work fine on your computer, locally, but once you put it on a server, you will see the image fadeout, then fadein and still be the same image and then swap to the new image all of a sudden. This happens because it has some loading time. If you want to fix this you'll need some other events. Or you could load all images into the page and then just swap the one that is currently shown.
Even thought this has been answered, here is a fiddle with your original code corrected. http://jsfiddle.net/goqz3coj/
Its better to see how your code should work instead of been giving a different code
$(document).ready(function() {
var imageName = ["head.jpg", "head3.jpg", "head4.jpg"];
var indexNum = 0;
$("#head1").click(function() {
$("#head1").fadeOut(300, function() {
$("#head1").attr("src", imageName[indexNum]);
indexNum++;
if (indexNum > 2) {
indexNum = 0;
}
$("#head1").fadeIn(500);
});
});
});
SECOND VERSION Waits for image load before showing again...
http://jsfiddle.net/goqz3coj/2/
By simply using .load you can wait for the image to load and then show.
$(document).ready(function() {
var imageName = ["http://placehold.it/200x200", "http://placehold.it/300x300", "http://placehold.it/400x400"];
var indexNum = 0;
$("#head1").click(function() {
$("#head1").fadeOut(300, function() {
$( "#head1" ).load(function() {
$("#head1").fadeIn(500);
// Handler for .load() called.
});
$("#head1").attr("src", imageName[indexNum]);
indexNum++;
if (indexNum > 2) {
indexNum = 0;
}
});
});
});
Jonas Grumann took your image urls as easier to show with actual images.
I'm having a strange problem that I can't quite figure out.
I have a normal image on a web page
<img src="images/logo.png"/> <!-- getting image from root directory -->
and I have some javascript code to replace the image source
function imageUpdate() {
var image = document.querySelectorAll("img");
for (var num = 0; num < image.length; image++)
image[num].src = image[num].src.replace("images/pic01.png", "images/other/pic02.png")
}
This code works fine which is great although it seems to fall down as soon as the src I want it replaced to is outside of my root directory such as "http://www.servername.com/pic03.png" // (this is an imaginary URL don't try to click it).
is there a reason this happens? is there a way around this?
The problem is that you are only replacing the last part of your original src. The src of the img tag first looks like this:
"http://yourserver.com/images/pic01.png"
...and after replacing "images/pic01.png" with you external URL, it looks like this:
"http://yourserver.com/http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png"
To avoid this problem you can try this:
function imageUpdate() {
var image = document.querySelectorAll("img");
for (var num = 0; num < image.length; num++) {
if (stringEndsWith(image[num].src, "images/pic01.png")) {
image[num].src = "http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png";
}
}
}
function stringEndsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1
}
There's also an error in your for loop, where you are incrementing image instead of num
Step-by-step explanation
imageUpdate()
Loop through each img tag and look at the src attribute
If src ends with "images/pic01.png" replace all of src with the new url
stringEndsWith()
Find index of given suffix (start looking for the suffix at the last possible position
the suffix can be located at)
If this index is found (is different from -1) return true, else return false
What target url are you assigning to it? Make sure that it is pointing to an absolute address (keep the http:// part at the beginning).
If the file is in the same server, you can still use relative file paths, and go up a parent folder by using two dots. For instance: ../someotherfolder/pic03.jpg
<script>
function imageUpdate() {
document.getElementById('imageT').src = 'test.jpg';
}
</script>
<img id='imageT' src="images/logo.png"/> <!-- getting image from root directory -->
JS Fiddle-Demo
There is an error in the link you are trying to use. The actual link should be:
http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png
Here is come code to demonstrate:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script>
function changeImage() {
document.getElementById('changeThis').src = 'http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png'
}
</script>
</head>
<body>
<img id="changeThis" src="http://www.wartburgseminary.edu/uploadedImages/Resources/small-twitter-icon.jpg">
<input type="button" value="Change" onClick="changeImage()">
</body>
</html>