Increment Number in Image Source On Click - javascript

Basically I want to create next and previous buttons for a JQuery Image Gallery I'm working on. Each button has an id of "next" and "prev" respectively. What I'm trying to do is change a number that is in the source of the main image in the gallery (which has an id of mainImg). I have been able to target the number within the source of each image but I can't seem to increment it correctly and then replace the current image's source number with the new, incremented number. I tried using a while loop, for loop, and if statement but none of them worked correctly. To see the gallery that I have so far, I have it uploaded here: http://tiger.towson.edu/~abarso2/463/projecta/index.html If you go into my script.js file you'll see a block commented out at the bottom. That is the function I have so far that targets the number within the image's source and parses it to an integer. Thanks in advance for any help.
Here's what I have currently:
(function(){
var mainImg = $('#mainImg').attr('src');
var mainImgStr = mainImg.charAt(mainImg.length - 5);
var mainImgNum = parseInt(mainImgStr);
$('#next').click(function(){
});
}());

This should solve your problem
$(function(){
var mainImg = $('#mainImg');
var slidshow = $('#slideShow');
$('#next').click(function(){
var src = mainImg.attr('src').replace('thumb','shot');
var next = $('img[src="' + src +'"]', slidshow).next();
if(next.length){
mainImg.attr('src',next.attr('src').replace('thumb','shot'));
}
});
$('#prev').click(function(){
var src = mainImg.attr('src').replace('thumb','shot');
var prev = $('img[src="' + src +'"]', slidshow).prev();
if(prev.length){
mainImg.attr('src',prev.attr('src').replace('thumb','shot'));
}
});
});

Here is the revised code. The regexp will work better. The user can click the next button multiple times but no image will be skipped as the main image will only go to the next if and when the next image is loaded. So if you click next quickly 5 times only the next image will show (not skipping 4 images).
(function(){
// replace all non digit characters from src
// only the last set of numbers so www.123.com/image7.jpg
// will give us 7
function getNumber(src){
return parseInt(src.replace(/[\d]+(?=[\/])/g,"")
.replace(/[^\d]/g,""),10);
}
// replaces last number of a source with the number provided
// www.123.com/imgage7.jpg will be www.123.com/image8.jpg
// if number 8 is given
function setNumber(src,num){
return src.replace(/[\d]+(?![\d])/g,num);
}
var $mainImg = $('#mainImg');
$('#next').click(function(){
var src= $mainImg.attr('src'),
mainImgNum = getNumber(src);
var $img=$(document.createElement("img"));
$img.data("checkNext",false);
$img.on("load",function(){
// image exsist, load it as main image src
if($img.data("checkNext")===true){
$img.remove();
}else{
$mainImg.attr('src',$img.attr('src'));
$("#prev").show(1000);
$img.data("checkNext",true);
$img.attr('src',setNumber($img.attr('src'),
new String(mainImgNum+2));
});
$img.on("error",function(){
if($img.data("checkNext")===true){
$("#next").hide(1000);
}
// clean up
$img.remove();
});
$img.attr('src',setNumber(src,new String(mainImgNum+1)));
});
}());

Related

javascript/html: Second onclick attribute

I have an image - image1.png. When I click a button the first time, I want it to change to image2.png. When I click the button for a second time, I want it to change to another image, image3.png.
So far I've got it to change to image2 perfectly, was easy enough. I'm just stuck finding a way to change it a second time.
HTML:
<img id="image" src="image1.png"/>
<button onclick=changeImage()>Click me!</button>
JavaScript:
function changeImage(){
document.getElementById("image").src="image2.png";
}
I'm aware I can change the image source with HTML within the button code, but I believe it'll be cleaner with a JS function. I'm open to all solutions though.
You'll need a counter to bump up the image number. Just set the maxCounter variable to the highest image number you plan to use.
Also, note that this code removes the inline HTML event handler, which is a very outdated way of hooking HTML up to JavaScript. It is not recommended because it actually creates a global wrapper function around your callback code and doesn't follow the W3C DOM Level 2 event handling standards. It also doesn't follow the "separation of concerns" methodology for web development. It's must better to use .addEventListener to hook up your DOM elements to events.
// Wait until the document is fully loaded...,
window.addEventListener("load", function(){
// Now, it's safe to scan the DOM for the elements needed
var b = document.getElementById("btnChange");
var i = document.getElementById("image");
var imgCounter = 2; // Initial value to start with
var maxCounter = 3; // Maximum value used
// Wire the button up to a click event handler:
b.addEventListener("click", function(){
// If we haven't reached the last image yet...
if(imgCounter <= maxCounter){
i.src = "image" + imgCounter + ".png";
console.log(i.src);
imgCounter++;
}
});
}); // End of window.addEventListener()
<img id="image" src="image1.png">
<button id="btnChange">Click me!</button>
For achieve your scenario we have to use of counter flag to assign a next image. so we can go throw it.
We can make it more simple
var cnt=1;
function changeImage(){
cnt++;
document.getElementById("image").src= = "image" + cnt + ".png";
}
try this
function changeImage(){
var img = document.getElementById("image");
img.src = img.src == 'image1.png' ? "image2.png" : "image3.png";
}
Just use an if statement to determine what the image's source currently is, like so:
function changeImage(){
var imageSource = document.getElementById("image").src;
if (imageSource == "image1.png"){
imageSource = "image2.png";
}
else if (imageSource == "image2.png"){
imageSource = "image3.png";
}
else {
imageSource = "image1.png";
}
}
This should make the image rotate between 3 different image files (image1.png, image2.png and image3.png). Bear in mind this will only work if you have a finite number of image files that you want to rotate through, otherwise you'd be better off using counters.
Hope this helps.
Check the below code if you make it as a cyclic:
JS
var imgArray = ["image1.png", "image2.png", "image3.png"];
function changeImage(){
var img = document.getElementById("image").src.split("/"),
src = img[img.length-1];
idx = imgArray.indexOf(src);
if(idx == imgArray.length - 1) {
idx = 0;
}
else{
idx++;
}
document.getElementById("image").src = imgArray[idx];
}
html
<button onclick=changeImage();>Click me!</button>
function changeImage(){
document.getElementById("image").attr("src","image2.png");
}

Change class on multiple img in array

This is my first post here, I always found solutions on this page, so thank you for that.
I have a problem with .removeClass and .addClass in my last program.
I load multiple pictures into array Frames and I want change all (previous-image) to (current-image) in frames[0]. Here is my code, it is change class only on second image. Here is code:
function loadImage() {
// Creates a new <li>
var li = document.createElement("li");
// Generates the image file name using the incremented "loadedImages" variable
var imageName = "graphics/img/Dodge_Viper_SRT10_2010_360_720_50-" + (loadedImages + 1) + ".jpg";
var imageName1 = "graphics/img/Dodge_Viper_SRT10_2010_360_720_50-" + (loadedImages + 1) + ".jpg";
/*
Creates a new <img> and sets its src attribute to point to the file name we generated.
It also hides the image by applying the "previous-image" CSS class to it.
The image then is added to the <li>.
*/
var image = $('<img>').attr('src', imageName).addClass("previous-image").appendTo(li) && $('<img>').attr('src', imageName1).addClass("previous-image light-image").appendTo(li);
// We add the newly added image object (returned by jQuery) to the "frames" array.
frames.push(image);
// We add the <li> to the <ol>
$images.append(li);
/*
Adds the "load" event handler to the new image.
When the event triggers it calls the "imageLoaded" function.
*/
$(image).load(function() {
imageLoaded();
});
};
function imageLoaded() {
// Increments the value of the "loadedImages" variable
loadedImages++;
// Updates the preloader percentage text
$("#spinner span").text(Math.floor(loadedImages / totalFrames * 100) + "%");
// Checks if the currently loaded image is the last one in the sequence...
if (loadedImages == totalFrames) {
// ...if so, it makes the first image in the sequence to be visible by removing the "previous-image" class and applying the "current-image" on it
frames[0].removeClass("previous-image").addClass("current-image");
/*
Displays the image slider by using the jQuery "fadeOut" animation and its complete event handler.
When the preloader is completely faded, it stops the preloader rendering and calls the "showThreesixty" function to display the images.
*/
$("#spinner").fadeOut("slow", function() {
spinner.hide();
showThreesixty();
});
} else {
// ...if not, Loads the next image in the sequence
loadImage();
}
};
This is, how it looks in browser:
<ol><li><img src="graphics/img/Dodge_Viper_SRT10_2010_360_720_50-1.jpg" class="previous-image"><img src="graphics/img/Dodge_Viper_SRT10_2010_360_720_50-1.jpg" class="light-image current-image"></li></ol>
This is, what I want:
<ol><li><img src="graphics/img/Dodge_Viper_SRT10_2010_360_720_50-1.jpg" class="current-image"><img src="graphics/img/Dodge_Viper_SRT10_2010_360_720_50-1.jpg" class="light-image current-image"></li></ol>
When I change this
var image = $('<img>').attr('src', imageName).addClass("previous-image").appendTo(li) && $('<img>').attr('src', imageName1).addClass("previous-image light-image").appendTo(li);
to this
var image = $('<img>').attr('src', imageName1).addClass("previous-image light-image").appendTo(li) && $('<img>').attr('src', imageName).addClass("previous-image").appendTo(li);
it still change only second img. Any help?
var image = $('<img>').attr('src', imageName).addClass("previous-image").appendTo(li) && $('<img>').attr('src', imageName1).addClass("previous-image light-image").appendTo(li);
is not doing what you think it is. It's only using the second element you declare. They both get appended to the page (because the appendTo method runs), but && is a logical operator, it's not used for concatenation, so the variable "image" only contains the second image you declared.
This will work instead:
var image = $('<img>', { "src": imageName, "class": "previous-image" });
image = image.add($('<img>', { "src": imageName1, "class": "previous-image light-image" }));
image.appendTo(li);
If you are just trying to replace all the previous-image classes with current image then you can do this:
$('img.previous-image').each(function(){
$(this).addClass("current-image").removeClass("previous-image");
});

Javascript Slider title replace html for title just working on 1st item

Hi im building a slider using jquery tools.. here is my code http://jsfiddle.net/SmW3F/5/
Anyway, the problem is when you over the image is updated (the Main image) so each thumb update the main image on hover.
The problem is the title is just working for 1st item.. all other items are not updating the title..
here is this part of the code
var root = $(".scrollable").scrollable({circular: false}).autoscroll({ autoplay: true });
$(".items img").on("hover",function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("_t", "");
var tbtit = $("#tbtit").html();
var tbdesc = $("#tbdescp").html();
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").stop(true, true).fadeTo("medium", 0.5);
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
wrap.find(".img-info h4").replaceWith(tbtit);
wrap.find(".img-info p").replaceWith( tbdesc);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").trigger("mouseover");
var count = 0;
var scroll_count = 0;
setInterval(function(){
count++; // add to the counter
if($(".items img").eq(count).length != 0){
console.log(count);
$(".items img").eq(count).trigger("mouseover");
if(count % 5 === 0)
{
I found a couple of issues with your script, but first you have invalid markup in your page since you have multiple <div> elements with the same ids of tbtit and tbdescp. Id attributes should be unique in a HTML page so should change those to classes instead.
Now in your script you need to change the part where you retrieve the values of the title and the description of the image that is hovered to reference the sibling elements:
//THIS
var tbtit = $("#tbtit").html();
var tbdesc = $("#tbdescp").html();
//SHOULD NOW BE THIS
var tbtit = $(this).siblings('.tbtit').text();
var tbdesc = $(this).siblings('.tbdescp').text();
Finally when you update the text for your main image you want to set the content for your <h4> and <p> tags and not replace them completely, so use .text()
//THIS
wrap.find(".img-info h4").replaceWith(tbtit);
wrap.find(".img-info p").replaceWith( tbdesc);
//SHOULD NOW BE THIS
wrap.find(".img-info h4").text(tbtit);
wrap.find(".img-info p").text( tbdesc);

change image and caption

I am trying to work out a way to change the text that goes along with an image that is changed with javascript...
var x = 0;
var images = new Array(".jpg", ".jpg", ".jpg", ".jpg", ".jpg");
var i = setInterval(auto, 10000);
function auto() {
x++;
if (x == images.length) x = 0;
document.getElementById('bigImage').src = images[x];
}
function changeImage(img, imagetitle) {
document.getElementById('bigImage').src = img;
/* document.getElementById('mainimagetitle').innerHtml = imagetitle; */
}​​​
The commented part is how i suppose I could possibly change the text that goes with the image. How do i code the html. Should i use a with the id mainimagetitle?
If so, where and how do i add the different texts i want to show and hide?
As I see from your posting, this should do the job.
<img id="bigImage" src="img1.jpg" alt="" />
<div id="mainimagetitle"></div>
Be sure to add a (filled) src tag or you will get strange results in IE. As you start with the second image (x++ before the change) this will be no problem. Happy accident I think. ;-)
// Edit: Of course any element will do as long as you use the right id. But you didn't tell us what html you use (xhtml/html5/...).
You could potentially have another array that stores the captions for each of the images
var captions = ['Caption 1', 'Caption 2', ...];
Assuming the mainimagetitle is an id of a <p> element, you could do:
function changeImage(img, imagetitle) {
document.getElementById('bigImage').src = img;
document.getElementById('mainimagetitle').innerText = imagetitle;
}​​​
You can see the full example, based on your code here.

getting only last class assigned with this.class

Please can anyone see what is wrong in this code,
I have 2 class images with .man and .girl which contains 10 images in each.
next I have 2 div's #manCount and #girlCount which display total images number (10 in each)
when I move one image to #drop, It decrease 1 number from #manCount. So ther are total 10 images with class name .man, When the last image is moved to #drop I get a pop up that all images are processed.
now I also wants to process .girl class images but when i have both classess initialize it only work with .girl class.
function Dragger(c){
this.classname = c;
}
Dragger.prototype.Init = function(){
var classM = this.classname;
var manCount = parseInt($("#"+classM+"Count").text());
$("."+classM).draggable();
$("#drop").droppable({
drop: function() {
if(manCount <= 0){
alert("There are no more pictures left. " + classM );
return false;
}
manCount -= 1;
$("#"+classM+"Count").text(manCount);
}
});
};
var man = new Dragger("man");
man.Init();
above code runs just fine but when I initilize a new object
var man = new Dragger("man");
man.Init();
var girl = new Dragger("girl");
girl.Init();
It always pick girl object, any help where I am doing wrong?
It always return me female object on drag.
A screenshot of display: http://screensnapr.com/v/SrsyGz.png
Here is problem: http://screensnapr.com/v/hxrZYa.png
Thanks
Edit:
Ok i have fixed this issue by adding mouseover event, i am not sure how perfect it is thogh as i am pretty new to it but it works as expected
$(".man").mouseover(function(){
var man = new Dragger("man");
man.Init();
});
$(".girl").mouseover(function(){
var girl = new Dragger("girl");
girl.Init();
});
Maybe it’s because you are calling $('#drop').droppable() in the Init function, so it gets initiated more than once on the same element (#drop).

Categories