I have made a photo gallery in my website using the following:
/*Begin Photo Gallery Code*/
var images = ['g1.jpg', 'g2.jpg', 'g3.jpg', 'g4.jpg'];
function loadImage(src) {
$('#pic').fadeOut('slow', function() {
$(this).html('<img src="' + src + '" />').fadeIn('slow');
});
}
function goNext() {
var next = $('#gallery>img.current').next();
if(next.length == 0)
next = $('#gallery>img:first');
$('#gallery>img').removeClass('current');
next.addClass('current');
loadImage(next.attr('src'));
}
$(function() {
for(var i = 0; i < images.length; i++) {
$('#gallery').append('<img src="images/gallery/' + images[i] + '" />');
}
$('#gallery>img').click(function() {
$('#gallery>img').removeClass('current');
loadImage($(this).attr('src'));
$(this).addClass('current');
});
loadImage('images/gallery/' + images[0]);
$('#gallery>img:first').addClass('current');
setInterval(goNext, 4000);
});
It loads one picture at a time from a set of four pictures. Also I have four html files, each of them being relevant to one of the pictures. I want to use JavaScript/JQuery/AJAX to load the relevant html file's content along with the shown picture. Does anyone have an idea how I can do this?
Should I put the ajax files (4 html files) into a JavaScript array or something?
var ajaxPages=['ajax1.html','ajax2.html','ajax3.html','ajax4.html'];
Thanks in advance.
Unless the HTML files supposed to change somehow during their displaying, should either output them via your server-side code in hidden divs with the request (would be the correct way of doing it) or use AJAX to save them in a variable or create hidden divs.
First you need two arrays like this:
var ajaxPages=['ajax1.html','ajax2.html','ajax3.html','ajax4.html'];//File Names
var divPages=['div1','div2','div3','div4'];//Div ids in order
For the AJAX part you should use something like:
var getHtml = function(filename,divid){
$.post('html/'+filename, function(data) {
//The first argument is your file location
//Second one is the callback, data is the string retrieved
$('#'+divid).html(data);
});
}
$.each(ajaxPages,function(index,value){
getHtml(value,divPages[index]);
});
That should do it... Do tell me if you require further explanation.
EDIT:
var ajaxPages=['ajax1.html','ajax2.html','ajax3.html','ajax4.html'];
var divId="yourdivid";
var textArray=new Array();
var currentImg=0;
var getHtml = function(filename){
$.post('html/'+filename, function(data) {
textArray.push(data);//Save data inside the array textArray
});
}
$.each(ajaxPages,function(index,value){
getHtml(value,divPages[index]);
});
Then your goNext() method:
function goNext() {
var next = $('#gallery>img.current').next();
if(next.length == 0){
next = $('#gallery>img:first');
currentImg=0;
}else{
currentImg++;
}
$('#gallery>img').removeClass('current');
next.addClass('current');
loadImage(next.attr('src'));
$('#'+divId).html(textArray[currentImg]);//Adds text to div based on current picture
}
That should be working fine!
Related
I'm trying to make a JSP that refresh itself every 2scd approximately and keep what the user tip in input form.
My idea was to save the input with javascript, add them to the URL and refresh the page, then retrieve and set the input.
This is my JS code :
$(document).ready(function () {
function refreshPage(){
var mapValue = new Array();
var mapName = new Array();
var i = 0;
$(".positionInput").each(function() {
mapValue[i] = $(this).val();
mapName[i] = $(this).attr("name");
i++;
});
var parameters = "";
for(i = 0; i < mapName.length; i++){
if(mapValue[i] != ""){
parameters += "?" + mapName[i] + "=" + mapValue[i];
}
}
window.location.href = "http://localhost:8080/drawinguess/waitingplayer.jsp" + parameters;
setTimeout(refreshPage, 2000); //execute itself every 2s
}
refreshPage();
});
But the timer get crazy (even with 1mn delay), it refresh itself as fast as he can with window.location.href (without this, it's working fine)
Thanks in advance if you have any other idea or if I'm making something wrong
You could try and use local storage for this. The best way would be that instead of refreshing the entire page, you only refresh what is needed by having services set up and using an async function like fetch() to hit those services and update the page.
I am a beginner of javascript and jquery and i have 11 image tags in html. I want to
basically change sources of these tags using js and jquery. This code is not working and I am not getting any errors in firebug, can some one please tell me where I am doing wrong?
var imagesArray2=["01.png","02.png","03.png","04.png","05.png","06.png","07.png","08.png","09.png","10.png","11.png"];
var elementArray2 = ["#img1","#img2","#img3","#img4","#img5","#img6","#img7","#img8","#img9","#img10","#img11"];
var imagesArray,elementArray;
var elementInArray;
document ready
$(function(){
setInterval(Myfunction(),1000);});
my function code which has a loop based on elementsInArray variable value and it calls imageFadeAnimations function
function Myfunction(){
if(elementsInArray === 0){
imagesArray = imagesArray2;
elementArray = elementArray2;
elementsInArray = elementArray.length;
var imageChanges = Math.floor(Math.random()*elementsInArray);
imageFadeAnimations(imageChanges);
}
else
{
elementsInArray=elementArray.length;
imageChanges = Math.floor(Math.random()*elementsInArray);
imageFadeAnimations(imageChanges);
}
}
takes an integer as argument
function imageFadeAnimations(imageChanges){
for(var k = 0;k<imageChanges;k++){
var element = Math.floor(Math.random()*elementsinArray);
var image=Math.floor(Math.random()*elementsinArray);
imageChanger(elementArray[element],imageArray[image]);
elementArray.splice(element,1);
imagesArray.splice(image,1);
}
}
function imageChanger(b1,b2){
$(b1).fadeOut(500,function(){
$(b1).attr("src",b2);
$(b1).fadeIn(500);
});
}
You are making heavy weather out of something that jQuery can make very simple.
First wrap your images in an element (typically a div or a span) with id="imageContainer".
Now, if I understand correctly, your code will simplify to :
$(function() {
var imagesArray = ["01.png", "02.png", "03.png", "04.png", "05.png", "06.png", "07.png", "08.png", "09.png", "10.png", "11.png"],
$images = $("img", "#imageContainer");
setInterval(function() {
$images.each(function() {
var $img = $(this),
i = Math.min(imagesArray.length-1, Math.floor(Math.random() * imagesArray.length));
$img.fadeOut().promise().then(function() {
$img.attr("src", imagesArray[i]).fadeIn(500);
});
});
}, 1000);
});
EDIT 1
As #mplungjan points out below ...
If the img nodes were initialised with src attributes, then imagesArray can be composed by grabbing the srcs from the DOM as follows (replacing two lines above) :
var $images = $("img", "#imageContainer"),
imagesArray = $images.map(function() { return this.src; }).get();
I believe this jquery/zepto code is not the smaller, but the easier to understand:
function changeImg(){
$("#img1").attr('src', '01.png');
$("#img2").attr('src', '02.png');
$("#img3").attr('src', '03.png');
$("#img4").attr('src', '04.png');
$("#img5").attr('src', '05.png');
$("#img6").attr('src', '06.png');
};
$('.pictures a').click(function () {
var path = "place/of/images";
var pics = ['pic1.JPG',
'pic2.JPG',
'pic3.JPG',
'pic4.JPG'];
var i = 0;
var numberOfPics = pics.length - 1;
var vaheta = setInterval(function () {
$('body').css({ backgroundImage: 'url(' + path + pics[i] + ')' });
if (i == numberOfPics) {
i = 0;
} else {
i++;
}
}, 3000);
return false;
});
This is the code that is currently just changing background images for me. Now I found a topic here where it says you have to load the pictures as etc and there was this fiddle, http://jsfiddle.net/RnqQL/1/, this one, that is exactly what I want to do, but I don't quite know how to combine these two (my code and the fiddle).
The images will actually later be loaded with JSON from the server depending on the id of the link the person clicked to get this slideshow, this is too overwhelming for me...
I created fiddle at http://jsfiddle.net/xMrp3/1/
You can modify and use. I try to explain what i did with comments.
$('.pictures a').click(function () {
var path = "http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/";
$("#wrap").empty(); // clear wrap div content
$.getJSON('/echo/json/', function (pics) { // get json data
var pics = ['s-1.jpg', 's-5.jpg', 's-3.jpg']; // i override json response for demo
$.each(pics, function(i, pic) { // loop through pics array
$('<img/>').attr('src', path + pic).appendTo($("#wrap")); // append all images to #wrap div
});
if (animTimeout == null) // if we didnt started anim yet
anim(); // start animation
});
return false;
});
var animTimeout = null;
function anim() {
$("#wrap img").first().appendTo('#wrap').fadeOut(500);
$("#wrap img").first().fadeIn(500);
animTimeout = setTimeout(anim, 700);
}
I am making a photo gallery using jQuery and I want to have a button to display a random picture taken from the ones in the album. This picture should change every time the user clicks on the button. I have this code but every time I press the button I have the div#images fulling with the images instead of each one every time.
<script>
$('button').on('click', function() {
$.getJSON('images.json', function(data) {
imageList = data;
});
$('#images').append('<img src=' + imageList[Math.floor(Math.random() * imageList.length) + 1].img_src + '>').;
});
</script>
As you can see I read the images from a JSON file and randomize from 1 to the length of the file. Any suggestions would be helpful. Thank you in advance.
You need to clear the image div before adding the new image otherwise the images will keep adding.
<script>
$('button').on('click', function() {
$.getJSON('images.json', function(data) {
imageList = data;
//Also, move the code inside getJson(). getJson is asynchronous.
//Clear the images HTML
$('#images').empty();
$('#images').append('<img src=' + imageList[Math.floor(Math.random() * imageList.length) + 1].img_src + '>').;
});
});
</script>
Just wondering : Why don't you retrieve 1 random image via json call, instead of fetching all the images and then choosing one (Write the randomization code at the server) ?
Does the JSON data change? Otherwise, why do a request everytime? Separating the rand and image vars below isn't necessary, but might be easy to read for others later.
$('button').on('click', function() {
if ( typeof imageList == 'undefined' || !imageList.length )
{
$.getJSON('images.json', function(data) {
imageList = data;
var rand = Math.floor(Math.random() * imageList.length) + 1;
var image = $('<img />').attr('src', imageList[ rand ].img_src );
$('#images').html( image );
});
}
else
{
var rand = Math.floor(Math.random() * imageList.length) + 1;
var image = $('<img />').attr('src', imageList[ rand ].img_src );
$('#images').html( image );
}
});
Make sure you close the image tag as well as clear the existing image
<script>
$('button').on('click', function() {
$.getJSON('images.json', function(data) {
imageList = data;
});
$('#images').html("");
$('#images').append('<img src=' + imageList[Math.floor(Math.random() * imageList.length) + 1].img_src + '/>');
});
</script>
I have a folder with images in it and I'm loading those images using jQuery. This code:
$(function () {
var i=1;
for (i=1;i<=50;i++){
var curImg = "blog/wp-content/uploads/" + i + ".jpg";
var img = new Image();
$(img).load(function () {
$(this).hide();
$('#loader').removeClass('loading')
.append(this);
$(this).fadeIn();
}).error(function () {})
.attr('src', ''+curImg+'');
}
});
works fine for smoothly loading 50 images from this folder. I am trying to do 2 things:
I want to add a link like this: <a href='blog/wp-content/uploads/" + i + ".jpg' class='picLink'> to each individual image. I have tried using .wrap in my .load function here, but that isn't working for me. This just creates a nest of links (e.g. <a><a></a></a>).
Currently this finds the first 50 photo's, starting at number 1, and loads them. But if more photo's are added they won't be found, and the oldest will always be first. I would like it to find all photo's in the folder and print the newest (highest number) first. It can be presumed that there won't be more than, say, 4000 photo's. So would it be possible to do this loop in reverse, start at 4000, check if that photo exists and work down and just load photo's that exist in the folder?
Thanks in advance for any help, I hope the question is clear enough!
For 1. you can do something like this fiddle
$(function () {
var i=1;
for (i=1;i<=50;i++){
var curImg = "blog/wp-content/uploads/" + i + ".jpg";
var img = new Image();
$(img).load(function () {
$(this).hide();
$('#loader').removeClass('loading')
.append($('').append(this));
$(this).fadeIn();
}).error(function () {})
.attr('src', ''+curImg+'');
}
});
Also they may not be in order as some images may take longer to load than others.
For 2. I think you should get the image count server-side and inject it into the for loop something like,
for (i=<?php echo $count; ?>; i > <?php echo ($count>50?$count-50:0); ?>; i--){
assuming you're using php, where $count represents the amount of images in the folder.