Irene T.
Irene T.

Reputation: 1393

Fade Out And fade in Div with specific class and id

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

Answers (4)

Sachin Jain
Sachin Jain

Reputation: 21842

Couple of points:

  1. Ids should be unique. In case, you need same selector on group of elements, use class.
  2. 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

HTML

<div class="wrapper">
  <div class="add" id="1">Follow</div>
  <div class="added" id="1">Following</div>
</div>

JS

$('.wrapper').click(function () {
  $(this).find('.add').hide("fast");
  $(this).find('.added').fadeIn("slow");
});

Idea: Bind event listener on parent.

Upvotes: 0

n1kkou
n1kkou

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

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

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>

DEMO

Upvotes: 4

Adil
Adil

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.

Live Demo

$('.add').click(function () {
   $(this).hide("fast");
   $(this).next('.added').fadeOut("slow");
});

Upvotes: 1

Related Questions