I posted a question up yesterday that asked for some help on an image switching script I had written, thank you to all that helped me. I’ve extended the script and have run into a problem that I can’t for the life of me spot where the problem is.
HTML:
<div id="feature-image">
<h1><span>A random heading</span></h1>
</div>
<div id="feature-links">
<a class="a1" href="#">1</a>
<a class="a2" href="#">2</a>
<a class="a3" href="#">3</a>
</div>
JS + Jquery:
$(function(){
$('#feature-links a').click(function() {
if ($(this).hasClass('a-active')) {
return false;
} else {
var image = $(this).attr('class');
switchToImg(image, function() {
$('#feature-links a .a-active').removeClass('a-active');
$('#feature-links .' + image).addClass('a-active');
});
}
});
function switchToImg(image){
$('#feature-image').fadeOut('300', function(){
$('#feature-image').css('background-image','url(images/main_' + image + '.jpg)');
$('#feature-image').fadeIn('300');
});
};
In the script I check for a click on an <a> tag, each <a> tag has a class of (a1, a2, a3 etc.). Also, the active <a> has a class of ‘a-active’.
I’m attempting to check if a-active is set with this:
if ($(this).hasClass('a-active')) {
return false;
}
and cut the script there so that it doesn’t fade in and out the same image. However, the image continues to fade in and out despite my return false on checking for the class a-active and returning false. I am sure the problem is in the section where I am using .addClass and .removeClass but my knowledge of Javascript and Jquery is to flaky for me to properly debug this.
Could someone cast a critical eye over this please?
Thanks in advance.
You have incorrectly passed an anonymous function to your
switchToImg()function, which doesn’t accept one.Instead, try the following JS:
Tested in jsFiddle.
EDIT: I removed the call to
.stop(), it wasn’t necessary and introduced a bug.