Reputation: 1393
I am facing a little issue with some jquery code. I have some divs (look bellow)
<div class="add" id="1">Follow</div>
<div class="added" id="1">Following</div>
<div class="add" id="2">Follow</div>
<div class="added" id="2">Following</div>
I am trying when user clicks in each div with class add to fadeout the specific div and fade in the next div with class added.
Check my Code:
<script type="text/javascript">
$(document).ready(function($){
$('.add').click(function () {
$(this).find('.add').hide("fast");
$(this).find('.added').fadeIn("slow");
});
});
</script>
Upvotes: 1
Views: 4170
Reputation: 21842
Couple of points:
class
.this
reference contains the target on which event listener is added, So your this
context contains the element with add
class. jquery.find()
tries to match the selector on the children. That's why your code is not working.Just try this Jsbin Demo
<div class="wrapper">
<div class="add" id="1">Follow</div>
<div class="added" id="1">Following</div>
</div>
$('.wrapper').click(function () {
$(this).find('.add').hide("fast");
$(this).find('.added').fadeIn("slow");
});
Idea: Bind event listener on parent.
Upvotes: 0
Reputation: 3142
You can't have same id on multiple elements. Instead use a class
$('.add').on('click', function(){ $(this).fadeOut().next('.added').fadeIn(); });
Upvotes: 0
Reputation: 67207
ID's
must be unique and it should not be a number
. You have to set different ids
for your divs
. Additionally you have to hide the div with class .added
initially to achieve your need.
Because fadeIn
wont work on elements which are already visible.
Try,
<script type="text/javascript">
$(document).ready(function($){
$('.added').hide();
$('.add').click(function () {
$(this).hide("fast");
$(this).next('.added').fadeIn("slow");
});
});
</script>
Upvotes: 4
Reputation: 148120
You need to use $(this)
to hide current element and use next to hide .added
, also use unique ids to make your html valid.
The next element is already visible you probably need fadeOut()
to hide it.
$('.add').click(function () {
$(this).hide("fast");
$(this).next('.added').fadeOut("slow");
});
Upvotes: 1