image swap click jquery, 3 images - javascript

I want to be able to get the original image and cycle through 2 more images back to it so far I have this, but I dont know how to add an extra image
$('img').on({'click': function() {
var src = ($(this).attr('src') === '1.png') // current image
? '2.png'
: '1.png';
$(this).attr('src', src);
}});

One easy solution is to use an array with a counter variable and then loop over it in the click handler like
var images = ['//placehold.it/64/ff0000?text=1.png', '//placehold.it/64/00ff00?text=2.png', '//placehold.it/64/0000ff?text=3.png'],
counter = 0;
$('img').on({
'click': function() {
counter = ++counter >= images.length ? 0 : counter;
$(this).attr('src', images[counter]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="//placehold.it/64/ff0000?text=1.png" />

To avoid polluting global namespace I would use a closure as below. Check fiddle - Fiddle.
$('img').on('click', (function() {
var arr = [ ... paths to your images];
return function() {
var current = arr.indexOf( this.src );
current--;
this.src = current > 0 ? arr[ current ] : arr[0];
}
})() );

Related

Toggle images on click using jQuery

I have two images which I need to toggle on clicking on the image.
<img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png'
data-src='images/prof_arrow1.png' />
When the user click the image the src should get the value of data-swap and when you click again the src should change to data-src. This should keep happening just like a toggle. Any help appreciated.
$("#arrowRotate").click(function() {
var swapImage = $("#arrowGrey").attr("data-swap");
$("#arrowGrey").attr({
'src': swapImage,
id: 'arrowOrange'
});
});
This is where I have got so far.
Based on my understanding from your question, Hope this is the one you expect,
$("#arrowRotate").click(function() {
var _this = $(this);
var current = _this.attr("src");
var swap = _this.attr("data-swap");
_this.attr('src', swap).attr("data-swap",current);
});
DEMO Fiddle
Try This:
$("#arrowRotate").click(function(){
if($(this).attr('src')==$(this).attr('data-src'))
{
var a = $(this).attr('data-swap');
$(this).attr('src',a);
}
else
{
var b = $(this).attr('data-src');
$(this).attr('src',b);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id='arrowRotate' src='http://www.gettyimages.in/CMS/StaticContent/1391099215267_hero2.jpg' data-swap='http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg' data-src='http://www.gettyimages.in/CMS/StaticContent/1391099215267_hero2.jpg'>
This might help. I think this is the simplest way of swapping between images:
<img id="arrowRotate" src="images/img1.png" data-swap="images/img2.png" data-src="images/img1.png" onclick="swapImage()" />
function swapImage(){
var swapImage = $('#arrowRotate').attr('data-swap'),
currentImage = $('#arrowRotate').attr('src');
$('#arrowRotate').attr({
'src': swapImage,
'data-swap': currentImage
});
};
If I understand you right you can do it like this:
HTML
<img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png' data-src='images/prof_arrow1.png' data-swapped="false"/>
Javascript
$("#arrowRotate").click(function() {
var swapped = $(this).attr("data-swapped");
var init = 'false';
if(swapped === 'false'){
var swapImage = $(this).attr("data-swap");
init = true;
}else{
var swapImage = $(this).attr("data-src");
}
$(this).attr({
'src': swapImage,
'id': 'arrowOrange',
'data-swapped': init
});
});

div with an id wont accept any event handlers JavaScript. No Jquery

Im trying to pause a timed slideshow when you're hovering over a div
<div id="play_slide" onMouseOver="clearTimeout(playTime)"></div>
If i put onMouseOver="clearTimeout(playTime)" inside an li on the page, it'll pause, so I know my code is correct, it just wont work on the div! Also if i get rid of the id, it will alert when i put an alert function into an event handler
This is the js.
var playTime;
function playSlide()
{
var slideshow = document.getElementById("play_slide").style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if(indexPlay > images.length - 1)
{
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/"+images[indexPlay]+".png')";
playTime = setTimeout("playSlide()", 2500);
}
you can see this here: www.nicktaylordesigns.com/work.html
I would do it like this:
( and no inline script... just <div id="play_slide">Something</div> )
var playTime;
var indexPlay = 0;
var slideElement;
window.onload = function () {
slideElement = document.getElementById("play_slide");
slideElement.addEventListener('mouseenter', function () {
console.log('stop');
clearTimeout(playTime);
});
slideElement.addEventListener('mouseleave', function () {
console.log('continue');
playTime = setTimeout(playSlide, 2500);
});
playSlide();
}
function playSlide() {
var slideshow = slideElement.style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if (indexPlay > images.length - 1) {
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/" + images[indexPlay] + ".png')";
playTime = setTimeout(playSlide, 2500);
}
Fiddle
This issue is related to the script loading. Your script gets loaded after the DOM is processed so function doesn't get attached to the event.
If you are using jQuery then you can use below code.
$(function () {
$("#play_slide").mouseover(function(){
var playTime = 33;
clearTimeout(playTime);
});
});
If you don't want to use JQuery then you can do the same thing in JavaScript as below.
window.onload = function(){
document.getElementById("play_slide").onmouseover = function(){
var playTime = 33;
clearTimeout(playTime);
};
}
I got it! the div tag was somehow broken, I coded a div around it and gave it the event handlers and a class. That worked, then i simply changed the class to an id and got rid of the original div. Idk what was going on but it works now. Thanks for your suggestions!
Can you try this,
<div id="play_slide" onmouseover="StopSlide();">Stop</div>
<script>
var playTime;
var indexPlay;
function playSlide()
{
var slideshow = document.getElementById("play_slide").style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if(indexPlay > images.length - 1)
{
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/"+images[indexPlay]+".png')";
playTime = setTimeout("playSlide()", 2500);
}
function StopSlide(){
window.clearTimeout(playTime);
}
playSlide();
</script>

Getting the next image and previous image from an gallery

I am trying to code my own image gallery using html css jquery. I have a modal window to show the clicked in images. Inside my modal window I have a previous and next button.
My question is how can i show the previous images or next images when someone click that button.
Here's my jsFiddle
jquery code i am using to show clicked in images.
$(function(){
$('.gallery a').click(function(evt) {
evt.preventDefault( );
var imgPath = $(this).attr('href');
$('.gallery-overlay').show()
.find('.gallery-image').attr('src',imgPath);
return false;
});
});
Add this to your jQuery.
Declare a variable current image in your function and keep current image saved in that variable. Update the variable whenever current image is changed.
Updated jsfiddle
Click on the second image in the images and see the prev and next image then.
$('.gallery-control-previous').click(function(){
var imgPath = current_img.prev().attr('href');
current_img = current_img.prev();
$('.gallery-overlay').show().find('.gallery-image').attr('src',imgPath);
});
$('.gallery-control-next').click(function(){
var imgPath = current_img.next().attr('href');
current_img = current_img.next();
$('.gallery-overlay').show().find('.gallery-image').attr('src',imgPath);
});
If you have understood this answer, add checks to the code showing next, prev elemments only when they exist.
You can find how to do that,
here..
Updated.
Get the first child of next row, and pass that.
$('.gallery-control-next').click(function(){
if(current_img.next().length){
current_img = current_img.next();
}else{
current_img = current_img.parents(".row").next(".row").find("a:first");
}
var imgPath = current_img.attr('href');
$('.gallery-overlay').show().find('.gallery-image').attr('src',imgPath);
});
I have added img_no to each a tag to identify the current active image and get next or previous image
Working Demo
$(function () {
$('.gallery a').click(function (evt) {
evt.preventDefault();
var imgPath = $(this).attr('href');
var img_no = $(this).attr('img_no');
$('.gallery-overlay').show()
.find('.gallery-image').attr('src', imgPath).attr('img_no', img_no);
return false;
});
});
i = 1;
$('.row a img').each(function () {
$(this).attr('img_no', i);
$(this).parents('a').attr('img_no', i);
i++;
});
images_length = i - 1;
console.log(images_length);
$('.gallery-control-next').click(function () {
var img_no = $(this).parent().parent().find('.gallery-image').attr('img_no');
img_no++;
if (img_no > images_length) {
img_no = 1;
}
$('.row a').each(function () {
if ($(this).attr('img_no') == img_no) {
imgPath = $(this).attr('href');
}
});
$('.gallery-imagebox img').attr('src', imgPath).attr('img_no', img_no);
});
$('.gallery-control-previous').click(function(){
var img_no = $(this).parent().parent().find('.gallery-image').attr('img_no');
img_no--;
if (img_no <= 0) {
img_no = images_length;
}
$('.row a').each(function () {
if ($(this).attr('img_no') == img_no) {
imgPath = $(this).attr('href');
}
});
$('.gallery-imagebox img').attr('src', imgPath).attr('img_no', img_no);
});

jQuery fade image loop

I want to make a loop in my function so that the slideshow effect always restarts.
Here's my fiddle : http://jsfiddle.net/Be67B/
It's all good for the image 1 to go to image 2, but I want it to fade it back to the image 1, and then go the image 2, and so on...to always loop like that.
What do I need to add in my code to make this work?
Don't use a loop, just ask the browser to repetitively call your animation step :
setInterval(function(){
// your animation (in fact just a step)
}, someDelay);
Demonstration : http://jsfiddle.net/dystroy/nPh6S/
In this precise case, the animation is done with :
setInterval(function(){
$("#top").fadeOut(function() {
$(this).attr("src","http://1.bp.blogspot.com/-cFt5KNrHsHc/TZMH6XUBu-I/AAAAAAAAAR4/R6hOP7lffx0/s1600/apple-logo.png").fadeIn().delay(1000).fadeOut(function(){
$(this).attr('src', 'http://coreldrawtips.com/images/applebig.jpg').fadeIn().delay(1000);
});
}
);
}, 4000);
see this jquery cycle plugin:
http://jquery.malsup.com/cycle/
may be this is what you want
You can create a function that does the transition, which has a callback function as part of the fadeIn method that will call back to itself to trigger the next transition, and it would just be in a constant loop.
Here's your modified jsfiddle:
http://jsfiddle.net/Be67B/1/
HTML:
<img id="top" src="http://coreldrawtips.com/images/applebig.jpg" width="300" height="300" />​
Javascript:
$(document).ready(function(){
transition(false);
});
function transition(first)
{
var src = first ? "http://coreldrawtips.com/images/applebig.jpg" : "http://1.bp.blogspot.com/-cFt5KNrHsHc/TZMH6XUBu-I/AAAAAAAAAR4/R6hOP7lffx0/s1600/apple-logo.png";
$("#top").delay(1000).fadeOut(function() {
$(this).attr("src",src).fadeIn(function() {
transition(!first);
});
});
}
​
I just made this code:
$(document).ready(function(){
// images in the pool
var images=["http://1.bp.blogspot.com/-cFt5KNrHsHc/TZMH6XUBu- I/AAAAAAAAAR4/R6hOP7lffx0/s1600/apple-logo.png",
"http://1.bp.blogspot.com/-cFt5KNrHsHc/TZMH6XUBu-I/AAAAAAAAAR4/R6hOP7lffx0/s1600/apple-logo.png"];
// next image to display
var next = 0;
// interval beetween images
var INTERVAL = 1000;
// main function
var doCarrousel = function() {
$("#top").fadeOut(function() {
$(this).attr("src", images[next]).fadeIn(
function() {
setTimeout(doCarrousel, INTERVAL);
});
});
if (++next >= images.length)
next = 0;
};
//start carrousel
doCarrousel();
});
fiddler: http://jsfiddle.net/Be67B/
I would use a plugin. But you can do it by hand. I just recommend against changing the src of the images, because some browsers don't handle it very well, like safari not firing load event.
Instead, have all images inside a container, and cycle their visibility:
$(document).ready(function(){
var currentImage = $("#images img:first");
setInterval(function(){
currentImage.fadeOut();
if(currentImage.next().size())
currentImage = currentImage.next();
else
currentImage = currentImage.siblings().first();
currentImage.fadeIn();
}, 1000)
});
See fiddle: http://jsfiddle.net/Be67B/2/
Quick and dirty: jsFiddle example
function swap(img) {
img = (img == 'http://coreldrawtips.com/images/applebig.jpg') ? 'http://1.bp.blogspot.com/-cFt5KNrHsHc/TZMH6XUBu-I/AAAAAAAAAR4/R6hOP7lffx0/s1600/apple-logo.png' : 'http://coreldrawtips.com/images/applebig.jpg';
$('#top').delay(2000).fadeOut(function() {
$(this).attr('src', img)
}).fadeIn(function() {
setTimeout(function() {
swap(img)
}, 1000);
});
};
swap($('#top').attr('src'));​

Works only one function in implemented file

I have a js file with two functions, one in plain javascript and one using jQuery. I want both to work on window load. But if I enable both, only the plain javascript function works. When I disabled the "highliter" function "slideSwitch" works ok. What is the problem? How can I fix this?
function slideSwitch() {
var active = $('#slideshow img.active'),
next;
if (active.length == 0){
active = $('#slideshow img:last');
};
next = active.next().length ? active.next() : $('#slideshow img:first');
active.addClass('last-active');
next.addClass('active')
.css({opacity:0.0})
.animate({opacity:1.0}, 1000, function() {
active.removeClass('active last-active');
});
};
function startSlideShow() {
setInterval("slideSwitch()", 5000);
};
function highliter() {
var current = document.location.pathname;
var nav = document.getElementById('pages');
var a_tags = nav.getElementsByTagName('a');
for (var i = 0; i <= a_tags.length; i++) {
if (a_tags[i].getAttribute('href') === current) {
a_tags[i].parentElement.className = 'highlited';
}
}
};
window.onload = function() {
highliter();
startSlideShow();
};
Is there a javascript error occurring in highliter()? I see two possible issues:
Your for loop is checking <= length instead of < length, meaning you're exceeding the size of the array.
I could see there not being an element on the page with an id of 'pages', which would mean nav is null and the subsequent access on nav results in a null reference.
It isn't parentElement, it is parentNode.

Categories

Resources