I have wrote this javascript to show some images with id: imgFotogramma1/imgFotogramma2/ecc.. randomly in 8 different div with id Fotogramma1/Fotogramma2/ecc..:
function rullino() {
var immagini = new Array("strutture/1.jpg", "strutture/2.jpg", "strutture/3.jpg", "strutture/4.jpg", "strutture/5.jpg", "strutture/6.jpg", "strutture/7.jpg", "strutture/8.jpg", "strutture/9.jpg");
for (i = 1; i < 9; i++) {
var x = Math.floor(immagini.length * Math.random(1));
var imgId = "imgFotogramma" + i;
$(function () {
$(imgId).fadeIn(1000);
src = $(imgId).attr('src');
src = immagini[x];
alert(src);
});
}
setInterval("rullino()", 4000);
};
Now,this code start when body is loaded and its repeated every 4 seconds but i don't understand why the images are not displayed. I have started to work with Jquery not too much time ago and probably something are wrong.
I want to specify that: if i use normally javascript to assign to the src attribute the value of immagini[x],all work fine and the images are displayed.I have problem only to apply the fadein() motion.
I need a help to understand where is wrong,i have studied the fadeIn() API and i have tried to apply to my case.
Thanks in advance to anyone want to help me.
$(imgId).fadeIn(1000);
should be:
$('#'+imgId).fadeIn(1000);
Use # + idOfElemnt to select element with particular id.
You already doing it right. Just replace
var imgId = "imgFotogramma"+i;
With
var imgId = "#imgFotogramma"+i;
Since your are using the ID of the image, then your must have to use the "#" for id for applying the jQuery on it.
To select an ID, use # + elemID. Like this:
var imgId = "#imgFotogramma" + i;
Also, fade will not occur if the element is not hidden. First hide it, and then fade it in:
$(imgId).hide().fadeIn(1000);
Related
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);
I want to replace the number in the image src (eg. from eyes1 to eyes2) when I click a button.
moveRightBtn.on('click', function(){
var eyesImg = $('#eyesImg').get(0).src;
console.log(eyesImg) // <--- folder/folder/folder/img/eyes1.png
//iterate with one (eg. eyes1.png to eyes2.png) and change the src?
}
What is the best way to do this?
Just to expand on pmandell answer, you could also keep an increment (if that's what you want to do)
Also, it seems your image has an ID of eyesImg, so I've taken that into account also
var counter = 0;
moveRightBtn.on('click', function(){
$('#eyesImg').attr('src','folder/folder/folder/img/eyes' + counter + '.png');
counter++
}
Edit
Here's an example involving cats. Cats always help
http://jsfiddle.net/alexjamesbrown/6Cve9/
moveRightBtn.on('click', function(){
$(this).attr('src','new_src_string');
}
moveRightBtn.on('click', function(){
$(this).prop('src','folder/folder/folder/img/eyes2.png');
}
Use like this
var image = $(this).attr('src');
//alert(image);
var newimage = image.replace('1.png','2.png');
$(this).attr('src',newimage );
fiddle
Try this one:
$('#eyesImg').attr('src',$('eyesImg').attr('src').replace('eyes1','eyes2'));
Is anyone able to determine, how to stop the jQuery caching the image that it grabs, and displaying the same image around and around again?
Basically the image is been re-uploaded every 5 seconds, as it acts as a webcam (if you check the time stamp on the bottom right of the image, you can tell if it's been updated or not)
http://colourednoise.co.uk/scripts/index.htm
Thank you
(sorry I forgot to hit paste for the code)
$(function(){
$(document).ready(function() {
var imgs = ['http://www.ramseycommunityradio.co.uk/images/webcam.jpg', 'http://www.ramseycommunityradio.co.uk/images/webcam.jpg']
$("#webcam").attr('src', imgs[1]);
var refreshId = setInterval(function() {
$("#webcam").fadeOut("slow", function() {
var $el = $(this);
$el.attr('src', $.inArray($el.attr('src'), imgs) === 0 ? imgs[1] : imgs[0]);
$el.fadeIn("slow");
});
}, 2000);
});
You could try appending a changing query string onto the URL, this should stop caching if that is indeed your problem. I've seen this done with a time stamp here: how to generate and append a random string using jquery
So each time you generate an image you do:
var qs = (new Date).getTime();
var url = 'http://www.example.com/images/myimage.jpg?' + qs;
$(el).attr('src',url);
your code:
var imgs = ['http://www.ramseycommunityradio.co.uk/images/webcam.jpg', 'http://www.ramseycommunityradio.co.uk/images/webcam.jpg']
$("#webcam").attr('src', imgs[1]);
var refreshId = setInterval(function() {
$("#webcam").fadeOut("slow", function() {
var $el = $(this);
$el.attr('src', $.inArray($el.attr('src'), imgs) === 0 ? imgs[1] : imgs[0]);
// this condition is redundant, it will ultimately give the same result always
// because imgs[0]==imgs[1]
$el.fadeIn("slow");
});
}, 2000);
as far a JQuery is concerned you are not changing the SRC attribute (JQuery knows nothing about the content of the image). Try using two different names in the server-side like webcam0.jpg and webcam1.jpg and alternating between them.
One trick is t append a random query string URL which causes the image to reload from the server. The code could be something like:
setInterval(function() {
var img = $("#img").get(0);
img.src = img.src.replace(/\?.*/, "") + "?" + Math.random();
}, 5000);
I have a hell CMS to work with and am wondering if i can do the following with jQuery (or just straight up JS)
images are being displayed with no ID's or classes and I'd like to replace images based on their src value
pseudo code would be something like...
find img where src = /img/00789-reg-1.jpg';
and replace src value with ='img/much-better-img.jpg';
thanks -
Each image is a part of array provided by document.images. You can loop through images to find the image with the source you need.
var index=0;
while(document.images[index]){
alert(document.images[index].src);
index++;
}
Yes you can:
jQuery('img[src=/img/00789-reg-1.jpg]').attr('src','img/much-better-img.jpg');
Could you use:
var images = document.images;
var iLength = images.length;
for (var i=0; i<iLength; i++){
thisImage = images[i];
if (thisImage.src == "theOneThatIWantToReplace"){
thisImage.src = "myNewSrc"
break;
}
}
At least this doesn't involve hefting JQuery around if you don't need it.
You can use the Attribute Starts With Selector to find your images, then do the replace:
$("img[src^='/img']").each(function(){
$(this).attr("src", "new image");
});
var replace = {
"/img/00789-reg-1.jpg": "img/much-better-img.jpg",
"/img/another.jpg": "img/another-img.jpg"
}
for (var src in replace){
$("img[src="+src+"]").attr("src", replace[src]);
}
You can get all images and then check source of it
$('img').foreach(function(o){
if (o.attr('src')=='oldfile')
o.attr('src', 'newfile');
});
This is long, but I don't know other way.
I'm new to programming and was wondering how to make a customized alert that shows the id or class name of the object when I click on it. My site has a picture of 8 different animals, and I want it so that every time I click on one of the animals there's an alert with "This is a (animal's name)". Why won't my javascript code below work?
should i be using "this" instead of "parama"? i don't understand whether or not to have any parameters for my function clicky.
var images = new Array()
images[0] = "bison"
images[1] = "frog"
function clicky(parama){
for (entry in images){
if (parama.attributes["name"].value === images[entry]){
$(parama).onClick(alert("This is a" + parama.attributes["name"].value));
} else {
$(parama).onClick(alert("dang it");
}
}
}
using sort of a combination of both your answers, I figured out a way to do it with a lot less code than I originally had. Check it out! (images all had classes of "pic")
$('.pic').click(function(){
alert("This is a " + this.getAttribute('alt'))
});
I'd recommend to use the title or alt attribute on images instead of a JS array - that's more SEO friendly and semantic. Not to mention that alt is required on images to make your HTML valid - DEMO
var images = document.getElementsByTagName("img");
for ( var i = 0, count = images.length; i < count; i++ ) {
images[i].addEventListener("click", function() {
alert( this.getAttribute("alt") );
});
}
UPDATE
if you open to use jQuery - DEMO
$("img").on("click", function() {
alert( $(this).prop("alt") );
});
You can use .click() but it's recommended to use .on() instead to attach different kind of event listeners to elements. jQuery also provides a shorthand for getting the properties - .prop()