i did research for some hours but i can't find anything that is close enough to what I'm looking for. if you know a similar topic, please post the link.
i have not much experience with/in js. i want to create a small simple gallery.
i have a single image on the website. On click the image should be replaced by another one (image2). when i click now on this one, it should be replaced by image3 and so on.
i tried following but this doesn't work at all.
JS
$('.image1').click(function() {
$(this).attr('src', 'image2.jpg');
$(this).addClass('image2');
});
$('.image2').click(function() {
$(this).attr('src', 'image3.jpg');
$(this).addClass('image3');
});
…
when i get the last image (for example "image10"), the gallery should go to the start (image1).
thx for your help
You are looking for something called a Carousel, you have plenty opensource implementations of them on github. One of the most used is Lightbox : https://github.com/lokesh/lightbox2/blob/master/js/lightbox.js
Code is not very long, and you should 'easily' (between quotes :p) find part of it you need for your page.
To show using index() does indeed make sense here you go:
Fiddle
JS Code
$('.image').first().show();
$('.image').on('click', function () {
target = $('.image:visible').index();
lastElem = $('.image').length -1; //2 cause 3 images..
target === lastElem ? target = 0 : target = target + 1;
$('.image').hide()
$('.image').eq(target).show();
});
All images besides the first are initially hidden.
Write something like this. You don't need 10 different event handlers.
Create a common class .. for instance imageClass
$(document).on('click', '.imageClass', function () {
var src = $(this).attr('src'); //image1.png
var index = src.split('.')[0].replace('image',''); //get index `1`
//add 1 to index or reset to first image
index = (index == "10") ? 1 : parseInt(index) + 1;
$(this).attr('src', 'image' + index + '.jpg');
});
Related
I have 10 buttons each with a different image and text. I have each button to click on/off and if another button is clicked I want the active button to turn off. I am struggling with the latter.
var x = 300;
//port1
$('#port1').click(
function(){
var src = $('.image', this).attr('src');
//var srcs = $(this).attr('src');
if($(this).hasClass("highlight")) {
$('.butt').removeClass('highlight');
$('.image', this).attr('src', src.replace(/_dark(\.[^.]+)?$/, '_light$1'));
$('.p1').fadeOut(x);
}
else{
$('.butt').removeClass('highlight');
// $('.butt').attr('src').replace('_dark.png', '_light.png');
$('.butt img').each(function() {
var src2 = $('.image').attr('src').replace(/_dark(\.[^.]+)?$/, '_light$1');
$('.image').attr('src', src2);
});
$('.talk').fadeOut(x);
$(this).addClass('highlight');
$('.image', this).attr('src', src.replace(/_light(\.[^.]+)?$/, '_dark$1'));
$('.p0').fadeOut(x);
$('.p1').fadeIn(x);
}
});
The problem I am running into is that when I click the button, it changes the src on all the other buttons to be exactly the same as this one and does not just change the ending on the other sources to '_dark'. I thought adding this 'each' function would help and it did not.
Edit: I am new to coding but i attempted a jsfiddle: http://jsfiddle.net/messedUP90/yxjoxe41/
The random computers that appear was the effect I am going for and the code I wrote to do it before I remembered that each icon was going to be different. Look at the first button titled "un" for where the error I am talking about happens.
http://jsfiddle.net/gtf1dk0m/1/
You need to re-set the variable src.
This code does it:
$('.butt').each( function( index ) {
if ( $(this).attr('src') ) {
$(this).attr('src', $(this).attr('src').replace(/_dark(\.[^.]+)?$/, '_light$1'));
}
});
ignore the fact that the image does not change color in the jsfiddle. it works in dreamweaver. :)
There is some strange code and naming conventions in this function... such as var src = $('.image', this).attr('src');... theres a lot unexplained by the question asked here and with no jsfiddle it's hard to imagine what you mean or see what HTML elements you're using...
so I will try to answer based on purely your description and not your code.
If you want to remove all instances of a class such as an active class you could simply do an each function however your later comments about it changing all other image sources once clicked is in this line $('.image').attr('src', src2);. You have effectively targeted all images under the class .butt which seems to be all of your images. Perhaps what you want is actually to iterate over all elements and remove the active state such as...
$(".butt img").each(function() {
//Remove Active Classes
if($(this).hasClass("activeImage")) {
$(this).removeClass("activeImage");
}
});
Then you are now free to take the clicked button and add its active state in...
$(".buttons").each(function() {
$(this).click(function() {
//Old Code
$(".butt img").each(function() {
//Remove Active Classes
if($(this).hasClass("activeImage")) {
$(this).removeClass("activeImage");
}
});
//New Code
$(this).addClass("activeImage");
});
});
Then in your CSS you could make sure that you have a rule like
.activeImage {
background-image: url("blah.png") !important;
/* You Get The Idea */
}
The output in HTML is something like this:
ProductImage1 ProductImage2 ProductImage3 ProductImage4
Color1 Color2 Color3 Color2 Color4 Color5 Color6
What I want to do is when I hover my mouse over any color above, an original (current) image of ProductImage will change to another one (to match the hovered color). And that original image will be back when mouse leaves.
Here is the javascript I've done for hovering over each ProductImage.
var sourceSwap = function () {
var $this = $(this);
var newSource = $this.data('alt-src');
$this.data('alt-src', $this.attr('src'));
$this.attr('src', newSource);
}
$(function () {
$('img.main').hover(sourceSwap, sourceSwap);
});
UPDATE
I excluded unnecessary parts from my question. The answer from #hunter worked very well when I tested it here jsfiddle.net/4dK2x/27. However it didn't work when I combined it with my php parts to create dynamic lists. I'm still looking around and trying to find out the problems. I will come back and update my answer if I find a solution for it.
Here's updated code which should work with as many sets of products as you need if you mimic a similar html structure
$('.image .toggles img').hover(function () {
var src = $(this).attr("src");
var $main = $(this).closest(".image").find(".main");
$main.attr("toggle", $main.attr("src")).attr("src", src);
},
function () {
var $main = $(this).closest(".image").find(".main");
$main.attr("src", $main.attr("toggle"));
});
Example: http://jsfiddle.net/4dK2x/1/
You could do this two ways, you can try it by using CSS:
#tagName{
background: url("yourImage.jpg");
}
#tagName:hover{
background: url("anotherImage.jpg");
}
this assumes you have a div tag around the image, you can also reference class id's etc. (read into CSS for more details).
or you could do it through JavaScript
lets say you are not using JQuery (i need to familiarize myself more with JQuery)
var image1 = document.getElementById("nameofDivTag");
//on hovering kinda forgotten the JS version of hovering, JQuery has probably easier way
image1.style.background("url:("aDifferentImage.jpg"));
if i am wrong yay! if not yay!
hope it helps
I'm currently using the jquery-based iviewer for an online image gallery. This is the code being used to call the initial iviewer source image (edited for brevity):
var $ = jQuery;
$(document).ready(function(){
var iv1 = $(".viewer").iviewer({
src: "/folder/001.jpg",
});
After asking another question elsewhere on SO, I'm currently using this method to drive next/previous buttons by adding '1' to the current image src on click (all images are named incrementally using three digits - 001.jpg, 002.jpg and so on):
var i = 1;
$("#next").click(function()
{
i++;
iv1.iviewer('loadImage', "/folder/" + ("00" + i).slice(-3) + ".jpg");
return false;
});
However, the problem is that elsewhere on the same page I'm using some jquery code to change the displayed image in the iviewer on the basis of the class attribute of the relevant links (which are numbered similarly to the images - chimg001, chimg002 and so on):
$("ul.imageThumbs > li > a").click(function()
{
var k = $(this).attr("class");
iv1.iviewer('loadImage', "/folder/" + ((k).slice(-3)) + ".jpg");
return false;
});
(I'm new to both jquery and javascript so I'm happy to hear any suggested mods to the above.)
After using the above code to display new images, the next and previous buttons don't change relative to the newly-displayed image, but only according to the last image accessed via the next/previous buttons.
I'd like to be able to have the next and previous buttons working by first finding the current src of the iviewer and then add one to that, rather than the current method. Can this be done?
From reading the documentation for the plugin at the link you provided, there are a few parts that may be useful.
info(prop, dropRotation) - get some info about the image. Valid values for prop are: display_width, display_height - current physical dimensions of the image; orig_width, orig_height - dimensions of the original image; angle - current rotation angle; zoom - current zoom value in %; src - url of current image;
All the methods should be called through jquery ui notation: $('#viewer').iviewer('method', 'arg1', 'arg2')
So, try something like this:
$('.iviewer').iviewer('info','src');
I'm trying to make an infinitely rotating imagereel with jQuery. This imagereel shifts between images with an interval of 5000 milliseconds, then fading out the 'old' image and fading in the 'new' image. The image to be displayed has a style-attribute for "display:inline".
The code can be found below:
function switchImage(){
var selector = $('#fotoreel img[style="display: inline; "]');
var nextOne = $(selector).next();
if($(nextOne).length == 0)
{
var nextOne = $('#fotoreel img:first');
}
$(selector).fadeOut('normal',function(){
$(nextOne).fadeIn('normal');
});
var t = setTimeout("switchImage()",5000);
}
$(document).ready(function(){
setTimeout("switchImage()",5000);
});
The problem is that it works fine in Chrome, but in Firefox and in Opera it only shifts image one time. In IE it's worse; there it doesn't work at all.
Do you guys know a better way of infinitely looping with javascript? Now I use setTimeout() to call the function again, but that doesn't seem to work.
EDIT
Okay, thank you everyone! Such fast responds, awesome!
The solution that I used was the one of adding a class and searching for that instead of for the style. The display:inline didn't appear to be a problem, as it worked out, but all the browsers appeared to implement the jQuery fadeIn() function differently.
I namely wanted to filter EXACTLY on "display: inline ;", because the spaces were added in Chrome, but not in IE, FF or Opera. So that means the style attribute wasn't accurately at all to filter with. Stupid me! :)
I made sure that a class was added to the image that is showed currently, and find the next one by filtering on that class. Now it works like a charm.
Thank you all for your answers, I love this place! :D
This is most likely because you are checking the style attribute, which is very inconsistent in browsers. I.E. doesn't work at all or works with various amounts of white-space. Just simplify your selector to use a class or ":visible"
It's probably going to work better if you explicitly mark images with a class:
function switchImage(){
var selector = $('#fotoreel img.current');
var nextOne = $(selector).length ? $(selector).next();
if($(nextOne).length == 0)
{
var nextOne = $('#fotoreel img:first');
}
$(selector).fadeOut('normal',function() {
$(selector).removeClass('current');
$(nextOne).addClass('current').fadeIn('normal');
});
setTimeout(switchImage, 5000);
}
$(document).ready(function(){
$('#fortoreel img:last-child').addClass('current');
setTimeout(switchImage,5000);
});
Note also that in my calls to "setTimeout()" I pass a direct reference to the function instead of a string version of the code to call it.
This wasn't working because the browsers you mentioned did not like the display: inline selector you used.
I got it working using the following:
function switchImage() {
var selector = $('#fotoreel img:visible');
var nextOne = selector.next();
if (nextOne.length == 0) {
var nextOne = $('#fotoreel img:first');
}
selector.fadeOut('normal', function () {
nextOne.fadeIn('normal');
});
var t = setTimeout(switchImage, 5000);
}
$(document).ready(function () {
setTimeout(switchImage, 5000);
});
I need a regular expression that will properly work, the current one I have is breaking.
The goal is
Normal src for an image is:
Image.png
Using jQuery on hover I dynamically find the src of an image and replace it with ImageName-Dn.png
On hover off it sets it back to ImageName.png
My current solution:
$(document).ready(function(){
$(".myButton").hover(
function () {
var s = $(this).attr('src');
s = s.substring( 0, s.search(/(\.[a-z]+)$/) ) + '-Dn' + s.match(/(\.[a-z]+)$/)[0];
$(this).attr('src', s);
},
function () {
var o = $(this).attr('src');
o = o.replace(/-Dn\./, '.');
$(this).attr('src', o);
}
);
});
However for some reason the image at some point gets set to ImageName-Dn.png and then screws up and gets set to ImageName-Dn-Dn.png and so on and so forth. Any Help?
A quick fix is to test if the string doesn't already have -Dn in it:
if (!string.match(/-Dn\./))
Also, with the regexes, you don't need to manually split the string and do multiple searches. You can use grouping to receive what you need in a single replace instruction such as:
string.replace(/(.*)\.(.*)/, "$1-Dn.$2")
If you want to read up on regular expressions for Javascript: http://en.wikibooks.org/wiki/JavaScript/Regular_Expressions
are you doing this for a mouseover effect? Why not use image sprites? Effectively, you just need to create 1 image that contains both version of the image side by side and set it to the background of an element which will display it.
for example, a 10x10 image and it's mouseover version will become a 10x20 image with the original on top of the mouseover version.
you can then create a 10x10 div with the background-image set to the 10x20 image. Since only the top 10x10 will be displayed, you only see the original version.
Then in javascript you can simply attach to an event a call to
$(el).style.backgroundPosition = '0px -10px';
on the hover event and
$(el).style.backgroundPosition = '0px 0px';
to reset it
This will shift the background up on the mouse over. Not only is this cleaner than having to deal with regex for a simple image swap, it also reduces the number of files the page has to load.
Hope this helps!
function () {
var s = $(this).attr('src');
if( !s.match(/-Dn\.[a-z]+$/) ) {
s = s.substring( 0, s.search(/(\.[a-z]+)$/) ) + '-Dn' + s.match(/(\.[a-z]+)$/)[0];
$(this).attr('src', s);
}
},
function () {
var o = $(this).attr('src');
o = o.replace(/-Dn\./, '.');
$(this).attr('src', o);
}
(added conditional)