Sunday, 8 September 2013

HTML5/jQuery: Trying to replace each image in a list with a different image

HTML5/jQuery: Trying to replace each image in a list with a different image

I am using bxslider. I am trying to write some jQuery to replace each
image in the slider with a different image once a button is clicked.
HTML:
<!--Slider list-->
<ul class="bxslider">
<li><img src="/img/green1.png" /></li>
<li><img src="/img/green2.png" /></li>
<li><img src="/img/green3.png" /></li>
<li><img src="/img/green4.png" /></li>
</ul>
<!--Button(s)-->
<ul class="colour">
<li id="blue">Blue</li>
</ul>
jQuery:
(function() {
//Variables
var colourLis= $(".colour").children(),
listItems = $(".bxslider li img"),
imgSrc = [ 1, 2, 3, 4, ];
//Click button
listItems.each(function(index) {
colourLis.click(function() {
listItems.attr('src', '/img/' + ($(colourLis).attr("id")) +
imgSrc[index] + '.png');
});
});
})();
I know this looks and sounds confusing and that my code is probably quite
disorganised - I am rather new to this! Any general advice would be much
appreciated.
Anyway, the above jQuery is meant so that, upon clicking of "blue," each
of the four images in the slider would have their src altered to be
directed to a new image, changing the contents of the slider.
E.g. /img/green1.png would become /img/blue1.png and green2.png would
become blue2.png etc.
Thing is, this method doesn`t seem to be working consistently. I cant seem
to nail down what is wrong but the console is often telling me that it is
only loading image 4 for each instance. (I.e. blue4.png would be inserted
into each li after the button is clicked).
If anyone could help me out that would be lovely!
I am open to better ways to do this. As I say I am new so not sure what
the best way to do this kind of operation is. I wanted this function to be
able to scale so I could have multiple different buttons, i.e. blue, red,
orange etc.
Thanks in advance.
Sirrah

No comments:

Post a Comment