Jeremy Zhang Jeremy Zhang - 3 months ago 8
HTML Question

How to execute js code again whenever a class name change?

Sorry for my editting format in advance cos it's been a long time since I asked a question. I will try my best to follow all the rules.

So I have this list which works like an image carousel:

<div class="carousel">
<ul>
<li class="past"><img src="img1.png"/></li>
<li class="past"><img src="img2.png"/></li>
<li class="current"><img src="img3.png"/></li>
<li class="future"><img src="img4.png"/></li>
<li class="future"><img src="img5.png"/></li>
</ul>
</div>


Whenever I click on an image, the clicked item's class name will change to "current" and I will translateX
<ul>
to make "current"
<li>
look "centered". All of these are in "carousel"
<div>
.

However I have another div which has a background of an empty-screen iPhone mockup:

<div class = "iphone_screen">
<div>
<img class="display" src="blank_screen.png"/>
</div>
</div>


and I want to do this to the "iPhone"
<div>
:

var imgUrl = $("body").find(".current").find('img').attr('src');
$(".display").attr('src',imgUrl);


But this jQuery will only be executed once when I load the page.

So how do I execute my jQuery code again whenever I lick one of the
<li>
items and make the class name
current
change?

Update: Thank you all for the replies! I feel so stupid......I don't know why I ask this question.........I added a click function before and it didn't work.Then I started to look for alternatives. Now when I think about it, the selector must be wrong.

Answer

Since the event that drives everything comes from a click on the li you could run on a click for any li's (inside a ul) inside the carousel classed div.

$(".carousel > ul > li").click(function () {
  var imgUrl = $("body").find(".current").find('img').attr('src');
  $(".display").attr('src',imgUrl);
});