开发者

jQuery clickable row

I have a table, representing a calendar, that can expand and collapse table rows.

  <tr class="parent" id="month1">
    <th class="subheader">Januari</th>
    <th></th><th></th>
  </tr>
  <tr class="row child-month1" id="day-1">
    <td class="date"> 1 januari 2010</td>
    <td>Bedrag </td>
    <td>-817.0 </td>
  </tr>
  <tr class="row child-month1" id="day-2">
    <td class="date"> 2 januari 2010</td>
    <td>Bedrag </td>
    <td> 0 </td>
  </tr>

With jQuery I make it clickable:

<scri开发者_开发问答pt type="text/javascript">
$(document).ready(function() {    
  $('tr.parent').click(function(){
    $(this).siblings('.child-' + this.id).toggle();
    return false;
  });
});
</script>

The problem now, is that the window scrolls always to the top after a table row is clicked. I want it to stay at the scrolling position that it was before the click.

The child rows get collapsed as supposed to, but the document scrolls to the top immediately after the click, even though i have returned false at the end of .click... What am I doing wrong?


Even if you didn't return false in the click handler, the page shouldn't be scrolling in response to the click.

Is it perhaps that the page is short enough that when some of the rows collapse, the page gets enough shorter that it all fits within the viewport? (And so naturally the browser scrolls up to fill the viewport.)

Update And if that's the case, you might consider trying to preserve scrollTop during the call:

$(document).ready(function() {    
  $('tr.parent').click(function(){
    var scrollTop = document.body.scrollTop;        // <== Save the current value
    // *** Maybe append something to the page here to keep it tall***
    $(this).siblings('.child-' + this.id).toggle();
    // *** Maybe remove the appended thing now ***
    document.body.scrollTop = scrollTop;            // <== Restore it
    return false;
  });
});

If all of this is in a container other than body, you may need to try to preserve it in that container instead, but you get the idea. This may not be perfect depending on how much the height of the page has changed, but it may help.


Ok so I tried TJ's suggestions to solve the problem.

I changed var scrollTop = document.body.scrollTop to var scrollTop = window.pageYOffset because somehow document.body.scrollTop always returns 0 (don't know why). the pageYOffset returns the correct scroll position for me. I did all this in Firefox by the way.

I ended up with this code:

  <div id="bottomspacer" style="height: 1000px; display: none; "></div>
  <script type="text/javascript">
  $('tr.parent').click(function(){
    $('#bottomspacer').show();
    var scrollTop = window.pageYOffset;
    $(this).siblings('.child-' + this.id).toggle();
    document.body.scrollTop = scrollTop;
    $('#bottomspacer').hide();
    return false;
  });
  </script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜