Changing multiple images source using jquery (and some other thing as well) - javascript

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');
};

Related

Why my html element is not shown in the following function

my goal is to display a loading curtain when a query to Quick-Base takes too long.
I have the following code that I thought it was going to work but it somehow does not. Everything works except for the loading curtain because it is never executed when it should be.
My code:
<script>
window.onload = function(){
// .. more code here not related ...
function selectedValueChanged() {
$('#curtain').show();
var e = document.getElementById("record_id_select");
var value_selected = e.value;
var CO_picked_record_id = parseInt(value_selected);
var query_CO_line_details = "{'"+related_CO_fid+"'.EX.'"+CO_picked_record_id+"'}";
var records = getRecords(table_CO_line_details_DBID,query_CO_line_details);
var data_array = createArrayFromRecordsDrilled(records,CO_detail_record_categories);
var table_div = tableCreate(data_array,'table_container_1',"Please Enter Quantities",headerList);
$('#table_container_1').replaceWith(table_div);
$('#curtain').hide();
}
}
</script>
<div id='curtain' style='position:absolute;top:0;left:0;margin:0;background:rgba(255,255,255,.3); display:none; width:100%;height:100%;'><img id ="loading_text" src="loader.gif"></div>
</body>
The code works but the curtain is never shown even if the query takes a couple of seconds (as much as 6 seconds). If I comment out the line "$('#curtain').hide();" I can see the loading curtain working as expected but only after the query has finished. It is as if the function is not been executed line by line but it waits first to complete the query and then to show the curtain. I'm sure I'm missing something but I don't know what. Thank you.
use this instead(no need to add any HTML to page) :
function showLoading() {
if (document.getElementById("loadingDiv"))
return;
var div = document.createElement("div");
var img = document.createElement("img");
var span = document.createElement("span");
span.appendChild(document.createTextNode("Loading ..."));
span.style.cssText = "margin-top:50vh;font-family:IranSans;direction:rtl;color:#f78d24;"
img.src = "/images/LoadingImage.png";
img.style.cssText = "display:block;margin:auto;margin-top:calc(50vh - 64px);width:128px;height:128px;"
div.style.cssText = "position:fixed;width:100vw;height:100vh;background-color:rgba(0,0,0,0.85);top:0px;left:0px;z-index:10000;text-align:center";
div.id = "loadingDiv";
div.appendChild(img);
div.appendChild(span);
document.body.appendChild(div);
}
function hideLoading() {
var div = getElementById("loadingDiv");
if (div)
document.body.removeChild(div);
}
The solution as #keith suggested was to "transform" the getRecords function from synchronous to asynchronous.
I ended up making the whole function selectedValueChanged() "asynchronous" by using the setTimeout trick.
One solution that worked for me was the following:
function selectedValueChanged() {
var e = document.getElementById("record_id_select");
var value_selected = e.value;
var CO_picked_record_id = parseInt(value_selected);
var query_CO_line_details = "{'"+related_CO_fid+"'.EX.'"+CO_picked_record_id+"'}";
var records = getRecords(table_CO_line_details_DBID,query_CO_line_details);
var data_array = createArrayFromRecordsDrilled(records,CO_detail_record_categories);
var table_div = tableCreate(data_array,'table_container_1',"Please Enter Quantities",headerList);
$('#table_container_1').replaceWith(table_div);
}
}
function loadingSelectedValueChanged(callbackFunct){
setTimeout(function(){
callbackFunct()
$('#curtain').hide();
},10);
}
function selectedValueChangedUP() {
$('#curtain').show();
loadingSelectedValueChanged(selectedValueChanged);
}
And now instead of calling selectedValueChanged, I call selectedValueChangedUP.
What SetTimeout does is to execute the function that receives as parameter after a given amount of time. This process is done in an "asynchronous" way.

Swap images with onclick

I have an incomplete script here that just needs to give a few adjustments of positions and add the exchange of images with the function Onclick of JavaScript but do not remember how to do more this exchange I would like to know what the error of the following code and how to fix, since I thank you.
// Like Normal e like Marcado
var imgLike01 = "images/mylike.png"
var imgLike02 = "images/like.png"
// Deslike Normal e deslike desmarcado
var imgDeslike01 = "images/mydeslike.png"
var imgDeslike02 = "images/deslike.png"
var likebtn = document.getElementById("likebtn");
var deslikebtn = document.getElementById("deslikebtn");
function like () {
likbtn.img.src = imgLike02;
}
function deslike () {
deslikebtn.img.src = imgDeslike02;
}
function Trade(){
if ($like).click(function() {
likbtn.img.src = imgLike01;
});
if ($deslike).click(function() {
deslikebtn.img.src = imgDeslike01;
});
}
Note This is the exchange of images from an old like system in JavaScript, a sum script and only missing image switching.
Add an eventListener to likebtn:
likebtn.addEventListener("click", like);
Do the same for deslikebtn.

Why is Javascript function not being called?

First Question on this site so I hope I do this right! I have a javascript function that I want to display an image (image1.jpg) when the page is loaded, and then every 2 seconds change the image by going through the loop. However only the first image is showing so it seems the JS function is not being called. Can anyone tell me if I am doing something wrong here because it looks fine to me so can't understand why it won't work. Thanks
<html>
<head>
<script type="text/javascript">
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var i = 1;
if(i>images.length-1){
this.src=images[0];
i=1;
}else{
this.src=images[i];
i++;
}
setTimeout("displayImages()", 2000);
}
</script>
</head>
<body onload="displayImages();">
<img id="myButton" src="image1.jpg" />
</body>
</html>
You need to move the line
var i = 1;
outside the displayImages -function or it will start from one each time!
EDIT: But using a global variable is not considered good practice, so you could use closures instead. Also as noted in other answers, you are referencing this which does not refer to the image object, so I corrected that as well as simplified the logic a bit:
<script type="text/javascript">
function displayImages( i ){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var img = document.getElementById('myButton');
img.src = images[i];
i = (i+1) % images.length;
setTimeout( function() { displayImages(i); }, 2000 );
}
</script>
<body onload="displayImages(0);">
You need the value of i to be available at each call, it can be kept in a closure using something like:
var displayImages = (function() {
var i = 0;
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
return function() {
document.getElementById('myButton').src = images[i++ % images.length];
setTimeout(displayImages, 2000);
}
}());
Also, since this isn't set by the call, it will default to the global/window object, so you need to get a reference to the image. That too could be held in a closure.
There are a couple of issues here that are stopping this from working.
First the var i = 1; needs to be moved outside the function to make the increment work. Also note that the first item in an array is 0, not 1.
Second you're using this to refer to change the image's src, but this is not a reference to the image. The best thing to do is use here is document.getElementById instead.
var i, button;
i = 0;
button = document.getElementById('myButton');
function displayImages() {
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if (i > images.length - 1){
button.src = images[0];
i = 0;
}
else{
button.src = images[i];
i++;
}
setTimeout(displayImages, 2000);
}
There's still some room for improvement and optimisation, but this should work.
You are reinitializing value of i every time, so change the following:
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if(!displayImages.i || displayImages.i >= images.length) displayImages.i = 0;
document.getElementById('myButton').src = images[displayImages.i];
displayImages.i++;
setTimeout(displayImages, 2000);
}
Functions are objects in JS and because of this:
you can pass them by reference and not as a string improving performance and readability
you can add fields and even methods to a function object like I did with displayImages.i
EDIT: I've realized that there was one more issue src was not being set for button.
Now I've fixed this and also made other improvements.
Here is the fiddle http://jsfiddle.net/aD4Kj/3/ Only image URLs changed to actually show something.
<script type="text/javascript">
var i = 1;
function displayImages(){
.......
........
Just make "i" Global. so that whenever displayImages being called it will not redefined to 1.
<html>
<head>
<script type="text/javascript">
var i = 1;
function displayImages() {
var images = ['img1.jpg', 'img2.jpg', 'img3.jpg'];
i++;
if (i > images.length - 1) {
i = 0;
}
$('#myButton').attr('src', images[i]);
setTimeout(displayImages, 2000);
}
</script></head>
<body onload="displayImages();">
<img id="myButton" src="img1.jpg" height="150px" width="150px"/>
</body>
</html>
Make i global.
here your are using displayImages() recursively and variable for index i. e i assign as local variable in function displayImages() , you need to assign it global variable i.e outside of the function also initialize it from i=0 as array index always start from 0,
your code become
var i = 0; // assign i global
function displayImages(){
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
if(i>images.length-1){
document.getElementById('myButton').src=images[0]; //get img by id
i=0; // to get first image
}
else{
document.getElementById('myButton').src=images[i]; //get img by id
i++;
}
setTimeout("displayImages()", 2000);
}

Loading A text along with a picture using AJAX

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!

random image; without repeating?

First off I'm not very familiar with javascript, thus here I am.
I have this code for my site to draw a random image. Working from this, how can I make the images not repeat? Thanks in adv! Code:
<script type="text/javascript">
var banner_list = ['http://i1233.photobucket.com/albums/ff389/lxluigixl/Cargo/LM_LogoMark4-4-2.gif', 'http://i1233.photobucket.com/albums/ff389/lxluigixl/Cargo/logobg_dome.png', 'http://i1233.photobucket.com/albums/ff389/lxluigixl/Cargo/logobg_brain.png']; $(document).ready(function() { var ran = Math.floor(Math.random()*banner_list.length);
$(".logobg img").attr(banner_list[ran]);
}); $(document).bind("projectLoadComplete", function(e, pid){
var ran = Math.floor(Math.random()*banner_list.length);
$(".logobg img").attr("src", banner_list[ran]);
}); </script>
After you display the image splice it out of the array, you can use banner_list.splice(ran, 1);. The arguments are .splice(index, howManyToRemove, howManyToInsert). Inserting is optional, so you can just use splice to start at the index of the image you're displaying and remove one. Make sure not to remove it until you're done referencing it.
You can use Array.splice() as Robert suggest with 2 Arrays. One for unsused and one for used images. Check my JSfiddle.
var images = ["http://www.fowkesauto.com/products_pictures/nutsbolt.jpg",
"http://i01.i.aliimg.com/photo/v0/114511763/Fasteners_Bolts_and_Nuts.jpg",
"http://us.123rf.com/400wm/400/400/DLeonis/DLeonis0810/DLeonis081000018/3706757-bolts-and-nuts-on-white.jpg",
"http://static3.depositphotos.com/1003288/173/i/950/depositphotos_1737203-Nuts-and-bolts.jpg"],
usedImages = [];
setInterval(function () {changeImage();},500);
var changeImage = function () {
var index = Math.floor(Math.random() * (images.length)),
thisImage = images[index];
usedImages.push(thisImage);
images.splice(index, 1);
if (images.length < 1) {
images = usedImages.splice(0, usedImages.length);
}
$("#image").attr("src", thisImage);
}

Categories