Problems using next() and prev() methods for cyclic gallery - javascript / jQuery - javascript

I'm new to javascript and jQuery. I'm trying to create an online gallery to see photos, using 2 buttons "next" and "prev". It must be cyclic so, for example, if I click "next" when the last photo is displayed, the next photo must be the first one.
I tried to use 3 variables: first img, last img and current img, so that I just need to do currimg = currimg.prev() (or next). And, for example, if the img displayed is the first one, I do currimg = lastimg.
$(document).ready(function() {
$("img").wrapAll("<div></div>");
$("img").nextAll().hide();
var firstimg = $("img:first");
var lastimg = $("img:last");
var currimg = firstimg;
$("#nextbutton").click(function(){
currimg.fadeOut("fast", function(){
(currimg==lastimg) ? currimg=firstimg : currimg=currimg.next();
currimg.fadeIn("fast");
});
});
$("#prevbutton").click(function(){
currimg.fadeOut("fast", function(){
(currimg==firstimg) ? currimg=lastimg : currimg = currimg.prev();
currimg.fadeIn("fast");
});
});
});
The problem is that the cycle works only if I press firstly prev. If I click next and then twice prev, it doesn't work and it shows nothing. Where is the problem?

The problem with your solution is that every time you assign to your currimg the values returned from currimg=currimg.next(); or currimg.prev(); you are assigning a new jQuery object.
This causes that when you make the comparison (currimg==firstimg) this will not be true even if both currimg and firstimg are pointing to the same DOM element.
In order to check if two jQuery objects point to the same DOM element you can use the is method.
So, your code should look something like:
$(document).ready(function() {
var $imgs = $("img");
$imgs.wrapAll("<div></div>");
$imgs.nextAll().hide();
var firstimg = $imgs.first();
var lastimg = $imgs.last();
var currimg = firstimg;
$("#nextbutton").click(function(){
currimg.fadeOut("fast", function() {
currimg = (currimg.is(lastimg)) ? firstimg : currimg.next();
currimg.fadeIn("fast");
});
});
$("#prevbutton").click(function(){
currimg.fadeOut("fast", function(){
currimg = (currimg.is(firstimg)) ? lastimg : currimg.prev();
currimg.fadeIn("fast");
});
});
});
Note that I have also stored all your images in $imgs so that there is no need to do multiple selections of the images on your script startup. The use of the ternary operator has also been changed in order to be clearer/cleaner.

Related

Load content in div from a href tag in jQuery

I want to load all images before displaying them in a slideshow. I have been searching a lot but nothing seems to work. This is what i have so far and it doesn't work. I am loading images from the <a> tag from another div.
$('.slideshow').load(function(){
if (loaded<length){
first = $(settings.thumb).eq(loaded).find('a').attr("href");
$('<img src="'+first1+'"/>').appendTo('.slideshow');
}
else{ $('.slideshow').show(); }
loaded++;
});
Add an event listener to each image to respond to when the browser has finished loading the image, then append it to your slideshow.
var $images = $("#div_containing_images img");
var numImages = $images.length;
var numLoaded = 0;
var $slideshow = $(".slideshow");
$images.each(function() {
var $thisImg = $(this);
$thisImg.on("load", function() {
$thisImg.detach().appendTo($slideshow);
numLoaded++;
if (numLoaded == numImages) {
$slideshow.show();
}
});
});
It's a good idea to also listen for the error event as well, in case the image fails to load. That way you can increase numLoaded to account for broken image. Otherwise, your slideshow will never be shown in the event the image is broken.
Also note, that by calling detach() followed by appendTo() I am am moving the image in the DOM. If instead, you want to copy the image, use clone() instead of detach().
* EDIT TO MODIFY USER'S EXACT USE CASE *
var $images = $("li.one_photo a");
var numImages = $images.length;
var numLoaded = 0;
$images.each(function() {
$('<img />',
{ src: $(this).attr("href") })
.appendTo('.slideshow')
.on("load error", function() {
numLoaded++;
if(numLoaded == numImages) {
$('.slideshow').show();
}
});
});
* EDIT #2 *
Just realized you were putting everything in the $(".slideshow").load() function. Since $(".slideshow") represents a DIV, it will never raise a load event, and the corresponding function will never execute. Edited above accordingly.

Fade In don't work

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

jQuery won't load updated images

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

javascript - trying to make an onClick alert based on id/class

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

Make image's z-index change on click

I've tried a lot of things, but nothing is working.
When I click on an mage, I want it's z-index to be "9999". When I click to show another image, I want the previous image's z-index to go back to "0".
So basically, I only want one image to show at a time - I want a specific function to run for each image.
http://jsfiddle.net/WarrenBee/a78R7/
PLEASE help me!
Change your JavaScript to this:
$('.char').click(function () {
$('.char img').css({'z-index' : '0'});
$(this).children('img').css({'z-index' : '9999'});
});
This will set the z-index of all imgs inside a char class back to 0, before setting the one that was clicked to 9999.
Just remember the last image and value and put the old value back:
var lastImage, lastZIndex;
$('.char').click(function () {
var thisImage = $(this).children('img');
if (lastImage) {
lastImage.css('z-index', lastZIndex);
}
lastImage = thisImage;
lastZIndex = thisImage.css('z-index');
thisImage.css({'z-index' : '9999'})
});
Updated fiddle
Ideally, avoid creating global variables by wrapping all of that in a function:
(function() {
var lastImage, lastZIndex;
$('.char').click(function () {
var thisImage = $(this).children('img');
if (lastImage) {
lastImage.css('z-index', lastZIndex);
}
lastImage = thisImage;
lastZIndex = thisImage.css('z-index');
thisImage.css({'z-index' : '9999'})
});
})();
Further updated fiddle

Categories

Resources