Question

Code

  <ul>
    {% for item in lis %}
    <li>
      <div id="single-toggle">|Toggle|</div>
      <div class="visible-when-folded">
        <div class="name">{{ item.name }}</div>
        <div class="date">{{ item.date }}</div>
      </div>

      <div class="invisible-when-folded">
        <div class="about">{{ item.about }}</div>
        <div class="contact_info">{{ item.contact_info }}</div>
      </div>
    </li>
    {% endfor %}
  </ul>

Example output code

  • |Toggle| Peter 24-04-1990 A friendly guy 0474657434
  • |Toggle| Martha 22-02-1984 An amazing gal 0478695675
  • |Toggle| William 12-11-1974 An oldie 0478995675

Desired behavior

I would like that whenever you click on |Toggle| the about(e.g. A friendly guy) and contact_info(e.g. 0474657434) part dissapear/reappear.

Attempt at solution

$(function(){
  $("#single-toggle").click(
    function(){ $("div.invisible-when-folded").toggle(); } );
});

But unfortunately this toggles the fields for each item in the list as opposed to only the one I click on.

Edit

views.py

from django.shortcuts import render_to_response
from django.template import RequestContext

def toggle(request):
    lis = [{'name':'Peter', 'date':'24-04-1990', 'about':'A friendly guy',
            'contact_info':'0474657434' }, 
          {'name':'Martha', 'date':'22-02-1984', 'about':'An amazing gal', 
            'contact_info':'0478695675' },
          {'name':'William', 'date':'12-11-1974', 'about':'An oldie', 
            'contact_info':'0478995675' }]

    return render_to_response('page.html', {'lis':lis},
      context_instance=RequestContext(request))
Was it helpful?

Solution

You need to pass the current object as context in the selector to get the element related to event source object. You also need to use class instead of id or generate unique ids for div with id = single-toggle as html elements are supposed to have unique ids.

Live Demo

I have give the div with id a class="single-toggle"

Change

$("div.invisible-when-folded").toggle();

To

$("div.invisible-when-folded", this).toggle();

You code

$(function(){
  $("#single-toggle").click(
    function(){ $("div.invisible-when-folded", this).toggle(); } );
});

OTHER TIPS

You need to focus the function on the div within the clicked div... The actual code you need to use is:

$(function(){
  $("#single-toggle").click(
    function(){ $("div.invisible-when-folded", this).toggle(); } );
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top