Changing img source by clicking button - javascript

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

Related

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

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.

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

Can I access and then replace image based on src value?, using jQuery or otherwise

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.

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