Techy
Techy

Reputation: 2654

Creating different functions on odd click and even click on link

I have 3 links which are the names of students.On clicking a link first time or odd number time,another div which contains the details of that student appears.On clicking the same link on second time or even number time, I need to hide the student div.Its working perfectly for me using data() event of jquery.

My requirement is if I click first student link,div with the details of first student will come.If I click the second student link,details of second student will come.If I again click on first link,the student div will hide since data() is associated with it(I think so). But I want to make it displayed because,previous click was on the second link.

My html is like this

<a href="" id="24" class="student_link">George</a>

<a href="" id="25" class="student_link">Leo</a>

<a href="" id="26" class="student_link">Kelm</a>

My jquery:

$("#sections ").on('click','.student_link',function(){
       var clicks = $(this).data('clicks');
      //alert(clicks);
      if (clicks) {
         $("#div_students").hide();
         //alert(1); 
      }
      else
      {
         $("#div_students").show();
         //alert(2);
      }

      $(this).data("clicks", !clicks);
      return false;
   });

That is if I click George for first time, the corresponding div of student will appear,If I click Leo without clicking George to hide the div,I need div of Leo should come.If I click George again,I need div with details of George should come.But for me the div is hiding since the variable click is already true for George.I need the div to be displayed if previous click was not on the current link.

Upvotes: 2

Views: 1307

Answers (3)

Krycke
Krycke

Reputation: 3186

You can so something similar to this:

$("#sections").on('click', '.student_link', function(){
    if( $("#div_students").data('viewing') == $(this).attr('id') ) {
        $("#div_students").hide().data('viewing', '');
    }
    else {
        $("#div_students").show().text($(this).attr('id'));
        $("#div_students").data('viewing', $(this).attr('id'));
    }
    return false;
});

Here's a working example: https://jsfiddle.net/7qwsguoq/

Upvotes: 1

Tushar
Tushar

Reputation: 87203

You can use the following code:

$("#sections").on('click', '.student_link', function () {
    var prevClickedId = $('#sections').data('prevId');

    if (prevClickedId != $(this).attr('id')) {
        // This was not the previous clicked element
    } else {
        // This was the previous clicked element
    }

    $('#sections').data('prevId', $(this).attr('id'));
    return false;
});

Upvotes: 3

kao3991
kao3991

Reputation: 402

Why don't just use jquery toggle() method? it hides element when it's visible, and shows when it's hidden.

Upvotes: 0

Related Questions