Reputation: 537
I am using Jquery slideToggle to show/hide a DIV element. When you click on a DIV element, it shows/hides the next DIV element.
When I have large number of DIV elements in my code, slideToggle is very slow and not responsive at the top of DOM Tree.
What is the reason for it to be slow at the top of DOM tree ? How can it be faster ?. Here is my sample code (This contains very few DIV elements, and it works well).
Note: slideToggle is working very well on DIV elements at the bottom of DOM Tree. Problem is with DIV elements at the top of DOM Tree.
<html>
<head>
<title> Home page </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$(".panel-heading").click( function() {
$(this).next().slideToggle();
});
});
</script>
</head>
<body>
<div id="container">
<div class="panel panel-default">
<div class="panel-heading nodeHeading">Panel heading</div>
<div class="panel-body" style="display:none;">Panel body</div>
</div>
<div class="panel panel-default">
<div class="panel-heading nodeHeading">Panel heading</div>
<div class="panel-body" style="display:none;">Panel body</div>
</div>
<div class="panel panel-default">
<div class="panel-heading nodeHeading">Panel heading</div>
<div class="panel-body" style="display:none;">Panel body</div>
</div>
<div class="panel panel-default">
<div class="panel-heading nodeHeading">Panel heading</div>
<div class="panel-body" style="display:none;">Panel body</div>
</div>
</div>
</body>
</html>
Upvotes: 2
Views: 1390
Reputation: 4999
A slideToggle
function is causing reflow (please see definition/difference of reflow and repaint), browser has to calculate the layout of the webpage and render it.
When you do slideToggle
at the bottom of dom tree, browser only needs to re-calculate the layout of the very bottom part of the webpage since toggle does not affect upper side of your toggled element. Obviously the very bottom part of the webpage is small, thus it takes little time before it starts to toggle.
While if you do slideToggle
at the top of dom tree, browser has to re-calculate the layout of almost the whole webpage, thus it takes more time before it starts to toggle.
Actually it seems no good solution to solve the problem if the there are too many elements, because the expensive operation reflow is unavoidable.
Upvotes: 1
Reputation: 987
Try make the duration of the slideToggle 'fast', like this :
$(this).next().slideToggle('fast','swing');
Here's a JSFiddle for you.
Upvotes: 0