I'm building an image slider in jQuery to bolster my knowledge of the language. In order to indicate that an image should be shown, I add a "selected" class to that <img>
tag. Additionally, in order to indicate that a nav button should be toggled on/off, I add an active / inactive class to that respective li
.
Example here:
$(document).ready(function(){
initPics();
currentImage = $('.selected').attr('id');
var navButton = $("li").find("img");
//show the right image when the nav button is clicked
$(navButton).on('click',function(){
$("#"+currentImage).removeClass('selected');
$("#"+currentImage).addClass('notSelected');
//change nav button when a different one is clicked
$('#navigation').children('li').children("img").removeClass('active');
$('#navigation').children('li').children("img").addClass('inactive');
});
if ($("li img").hasClass('active')){
$(this).find(".active").attr('src','images/button1.png');
} else {
$(this).attr('src','images/button2.png');
}
});
FYI The HTML that I'm working on looks like this:
Navigation buttons:
<ul id="navigation">
<li><img class="inactive" id="1" src="images/button2.png"></li>
Images in slider
<img src="images/slider1.jpg" id="image-1" class="slider selected">
The problem:
Whenever I click a new navigation button and remove the active
class from the nav buttons and add the inactive
class, it should also change the source of the image from button1.png
to button2.png
. It does change classes from active
to inactive
properly, but the img src
never changes. Why is this the case?
Edit: Link to a demo of what I'm talking about: demo
You have to put the code to change the image inside the click
function, otherwise it will be executed only one time: when the page loads. And obviously your image will never change anymore.
Here's the code:
$(navButton).on('click',function(){
$("#"+currentImage).removeClass('selected');
$("#"+currentImage).addClass('notSelected');
//change nav button when a different one is clicked
$('#navigation').children('li').children("img").removeClass('active');
$('#navigation').children('li').children("img").addClass('inactive');
// change image
$("li img.active").attr('src','images/button1.png');
$("li img.inactive").attr('src','images/button2.png');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.