As we have covered this tutorial with live demo to create dynamic Bootstrap Scrollspy with PHP and MySQL, so the file structure for this example is following.
- index.php
- scrollspy.js
Steps1: Create Database Table
As we will display navigation and content from MySQL database table, so first we will create MySQL database table scrollspy to store pages details and display it.
CREATE TABLE `scrollspy` (
`id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`description` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Steps2: Get Data From MySQL Database Table
Now we will get data from MySQL database table scrollspy and store in an array to display navigation title and content.
<?php
$sql = "SELECT id, title, description FROM scrollspy LIMIT 20";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$records = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
$records[] = $rows;
}
?>
Steps3: Create Bootstrap Scrollspy using Dynamic Content
First we will create navigation HTML using PHP array to display page title. To implement Scrollspy, we need to initialize target id to call with data-target, so created id navbar_scrollspy to use with data-target to create scrollspy.
<div id="navbar_scrollspy" class="navbar navbar-static">
<div class="navbar-inner">
<div class="container" style="width: auto;">
<a class="brand" href="#">PHPZAG</a>
<ul class="nav">
<?php
$count = 0;
foreach ($records as $record) {
$count++;
$class = '';
if($count == 1) {
$class = 'active';
}
echo "<li class='".$class."'><a href='#".$record['title']."'>".$record['title']."</a></li>";
}
?>
</ul>
</div>
</div>
</div>
Now we will create scrollspy behavior to created navigation by using data attribute data-spy="scroll" and data target data-target="#navbar_scrollspy". We also need to add CSS position: relative; to this element to add scrollspy behavior. We will create content HTML using PHP array with pages ids.
<div data-spy="scroll" data-target="#navbar_scrollspy" data-offset="50" class="scrollspy-nav">
<?php
foreach ($records as $data) {
echo "<h4 id='".$data['title']."'>".$data['title']."</h4>";
echo "<p>".$data['description']."</p>";
}
?>
</div>
Steps4: Use Scrollspy Functions
You can also use Scrollspy functions to create scrollspy behavior without using data attribute. For this, you need to use function .scrollspy() like below.
$('body').scrollspy({ target: '#navbar_scrollspy' })
When using scrollspy, you're adding or removing elements from the DOM, then you’ll need to call the refresh method like below:
$('[data-spy="scroll"]').each(function () {
var $spy = $(this).scrollspy('refresh')
})
You can view the live demo from the Demo link and can download the script from the Download link below.
Demo [sociallocker]Download[/sociallocker]