Nobody Nobody -4 years ago 81
HTML Question

cycle img src from array jQuery when div is clicked

I have read countless solutions on stack exchange and other websites and none of them are working for me. I want a

div
containing an
img
, with arrows either side. When you
click
the arrows, the javascript should change the
img src
to the next element in an array of images. I am new to javascript so please consider this when writing your response. Thanks. Here is a jfiddle http://jsfiddle.net/CZKAB/1/

Here is the html

<div id="filter-one" class="filter">
<div class="filter-nav">
<div id="prev-button"><img src="img/prv.png" alt="prev" title="Previous"></div>
</div>

<div id="filter-one-canvas">
<img src="img/shelter.png" id="filter-one-img" alt="filter1" title="Filter One">
</div>

<div class="filter-nav">
<a href="javascript:nextImage('#filter-one-img')" alt=""><img src="img/nxt.png" alt="next" title="Next"></a>
</div>
</div>


CSS

.filter {
height: 100px;
}

.filter-nav {
height: 52px;
width: 52px;
border-radius: 100%;
background-color: rgba(0,204,0,1);
opacity: 0.7;
float: left;
margin-top: 24px;
}

#filter-one img {
float: left;
}


Javascript

$(document).ready(function() {

var filterOneImages = new Array();

filterOneImages[0] = new Image();
filterOneImages[0].src = '../img/shelter.png';

filterOneImages[1] = new Image();
filterOneImages[1].src = '../img/food.png';

filterOneImages[2] = new Image();
filterOneImages[2].src = '../img/energy.png';

filterOneImages[3] = new Image();
filterOneImages[3].src = '../img/transport.png';

filterOneImages[4] = new Image();
filterOneImages[4].src = '../img/economy.png';

/*------------------------------------*/

function nextImage(element)
{
var img = document.getElementById(element);

for(var i = 0; i < filterOneImages.length;i++)
{
if(filterOneImages[i].src == img.src)
{
if(i === filterOneImages.length){
document.getElementById(element).src = filterOneImages[0].src;
break;
}
document.getElementById(element).src = filterOneImages[i+1].src;
break;
}
}
}

$('div.filter-nav').mouseenter(function() {
$(this).fadeTo('fast', 1);
});
$('div.filter-nav').mouseleave(function() {
$(this).fadeTo('fast', 0.7);
});
});

Answer Source

You are changing the src attribute of the div containing the img and not the img itself, replace:

$("#filter-one-img").attr(...

with

$("#filter-one-img img").attr(...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download