— jQuery Price Range Slider With Products Interface

In this post we will learn how to create a price range slider using jQuery and jQuery UI. First of all we need to download jQuery and jQuery UI’s slider component js. If you see any room for improvement, or if you can add something than go ahead and comment and I will definitely give it a look for possible inclusion.

sourcedemo

Download jQuery from here → Link (jQuery v 1.4)

Now go to jQuery UI and click on Themes then click on “Download theme button”

After clicking “Download Theme” you can configure your download as we don’t want all the files so click on “Deselect all components” then check “Slider” component and click on download button to download all the necessary files.

Unzip it once downloaded, you will find following folders in it. Copy js folder in your project folder then go to css folder > custom theme and copy images folder and jquery-ui-1.8rc1.custom.css too.

Ok we are all set to do some coding now :) ..

Markup

Create a file of  name “index.php” and paste following code in it.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link type="text/css" href="jquery-ui-1.8rc1.custom.css" rel="stylesheet" />
        <script type="text/javascript" src="js/jquery-1.4.1.min.js"></script>
        <script type="text/javascript" src="js/jquery-ui-1.8rc1.custom.min.js"></script>
        <script type="text/javascript">
            $(function() {
                $("#slider").slider(); // initializing slider
            });
        </script>
        <title></title>
        <style type="text/css">
            body{font-size: 12px;}
            .left{float:left;}
            .clear{clear:both}
            #wrapper{margin:40px auto;width:940px}
            #leftSlider{width: 200px;margin-right: 30px;}
            #products{width:710px}
            #products ul{
                list-style: none;
                margin:0px;padding:0px
            }
            #products ul li{
                margin:4px;
                float:left;
                height:180px;
                width:200px;
                background-color: #333;
                -moz-border-radius:6px;
                -webkit-border-radius:6px;
                -khtml-border-radius:6px;
            }
        </style>
    </head>

    <body>
        <div id="wrapper">
            <div class="left" id="leftSlider">
                <div id="slider"></div>
            </div>
            <div class="left" id="products">
                <ul>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                </ul>
            </div>
        </div>

    </body>
</html>

Adding Range To Slider

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link type="text/css" href="jquery-ui-1.8rc1.custom.css" rel="stylesheet" />
        <script type="text/javascript" src="js/jquery-1.4.1.min.js"></script>
        <script type="text/javascript" src="js/jquery-ui-1.8rc1.custom.min.js"></script>
        <script type="text/javascript">
            $(function() {
                $slider = $("#slider");//Caching slider object
                $amount = $("#amount");//Caching amount object
                $slider.slider({
                    range: true, // necessary for creating a range slider
                    min: 0, // minimum range of slider
                    max: 500, //maximimum range of slider
                    values: [75, 300], //initial range of slider
                    slide: function(event, ui) { // This event is triggered on every mouse move during slide.
                        $amount.html('$' + ui.values[0] + ' - $' + ui.values[1]);//set value of  amount span to current slider values
                    }
                });

                $amount.html('$' + $slider.slider("values", 0) + ' - $' + $slider.slider("values", 1));
            });
        </script>
        <title></title>
        <style type="text/css">
            body{font-size: 12px;font-family:"Arial","Helvetica","Verdana","sans-serif";}
            .left{float:left;}
            .clear{clear:both}
            #wrapper{margin:40px auto;width:940px}
            #leftSlider{width: 200px;margin-right: 30px;}
            #range{margin-bottom: 20px;}
            #products{width:710px}
            #products ul{
                list-style: none;
                margin:0px;padding:0px
            }
            #products ul li{
                margin:4px;
                float:left;
                height:180px;
                width:200px;
                background-color: #333;
                -moz-border-radius:6px;
                -webkit-border-radius:6px;
                -khtml-border-radius:6px;
            }
            #amount{font-size: 14px;text-shadow:0px 1px 0px #ccc}
        </style>
    </head>

    <body>
        <div id="wrapper">
            <div class="left" id="leftSlider">
                <div id="range">Price Range <span id="amount"></span></div>
                <div id="slider"></div>
            </div>
            <div class="left" id="products">
                <ul>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                </ul>
            </div>
        </div>

    </body>
</html>

Data From Database

First create a database of any name then create a table of following structure.

CREATE TABLE `products` (
`id` INT NOT NULL AUTO_INCREMENT ,
`image_url` TEXT NOT NULL ,
`price` INT( 4 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ;

we have not included field like “product_name” or “product_description” because they are not needed in this demo.

Insert some dummy data so that we can fetch and show it using PHP

INSERT INTO `products` (`id`, `image_url`, `price`) VALUES (NULL, 'product1.jpg', '200'), (NULL, 'product2.jpg', '120'), (NULL, 'product3.jpg', '80'), (NULL, 'product4.jpg', '320'), (NULL, 'product5.jpg', '400'), (NULL, 'product6.jpg', '480'), (NULL, 'product7.jpg', '500'), (NULL, 'product8.jpg', '270'), (NULL, 'product9.jpg', '370');

Adding PHP

Create a file of name “slider.php” and paste the following code in it

<?php
// connect to MySQL
mysql_connect('localhost', 'root', '') or
        die ('Unable to connect. Check your connection parameters.');
// select the correct database
mysql_select_db('sliderDemo') or die(mysql_error());

//get the minimum price of products
function minSliderValue() {
    $query = "SELECT min(price) as minValue from products";
    $result = mysql_query($query) or die(mysql_error());
    if(mysql_num_rows($result) > 0) {
        $row = mysql_fetch_assoc($result);
        return $row['minValue'];
    }
}

//get the maximum price of products
function maxSliderValue() {
    $query = "SELECT max(price) as maxValue from products";
    $result = mysql_query($query) or die(mysql_error());
    if(mysql_num_rows($result) > 0) {
        $row = mysql_fetch_assoc($result);
        return $row['maxValue'];
    }
}

//Dispaly products
function showProducts($where='') {
    $query = "SELECT * from products";
    if($where != '') {
        $query = $query .' where '. $where;
    }
    $result = mysql_query($query);
    if(mysql_num_rows($result) > 0) {
        $html = '<ul>';
        while($row = mysql_fetch_assoc($result)) {
           $html .= "
               <li>
                    <img src='images/products/{$row['image_url']}'/>
                    <span class='price-tag'>Price: $ {$row['price']}</span>
               </li>
            ";
        }
        $html .= '</ul>';
    }
    else{
        $html = 'Sorry No Records Found';
    }
    return $html;
}
?>

Edit your index.php as the following code so that it can show data from database.

<?php
include 'slider.php';
$minValue = minSliderValue(); //Get minimum price of product for slider min value
$maxValue = maxSliderValue(); //Get maximum price of product for slide max value
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link type="text/css" href="jquery-ui-1.8rc1.custom.css" rel="stylesheet" />
        <script type="text/javascript" src="js/jquery-1.4.1.min.js"></script>
        <script type="text/javascript" src="js/jquery-ui-1.8rc1.custom.min.js"></script>
        <script type="text/javascript">
            $(function() {
                $slider = $("#slider");//Caching slider object
                $amount = $("#amount");//Caching amount object
                $slider.slider({
                    range: true, // necessary for creating a range slider
                    min: <?php echo $minValue;?>, // minimum range of slider
                    max: <?php echo $maxValue;?>, //maximimum range of slider
                    values: [<?php echo $minValue;?>, <?php echo $maxValue?>], //initial range of slider
                    slide: function(event, ui) { // This event is triggered on every mouse move during slide.
                        $amount.html('$' + ui.values[0] + ' - $' + ui.values[1]);//set value of  amount span to current slider values
                    }
                });

                $amount.html('$' + $slider.slider("values", 0) + ' - $' + $slider.slider("values", 1));
            });
        </script>
        <title></title>
        <style type="text/css">
            body{font-size: 12px;font-family:"Arial","Helvetica","Verdana","sans-serif";}
            .left{float:left;}
            .clear{clear:both}
            #wrapper{margin:40px auto;width:940px}
            #leftSlider{width: 200px;margin-right: 30px;}
            #range{margin-bottom: 20px;}
            #products{width:710px}
            #products ul{
                list-style: none;
                margin:0px;padding:0px
            }
            #products ul li{
                background-color:#333333;
                float:left;
                height:127px;
                margin:4px;
                padding:8px;
                width:190px;
                -moz-border-radius:6px;
                -webkit-border-radius:6px;
                -khtml-border-radius:6px;
                position: relative;
            }
            .price-tag{-moz-border-radius-bottomright:6px;
                       -moz-border-radius-topright:6px;
                       -webkit-border-radius-bottomright:6px;
                       -webkit-border-radius-topright:6px;
                       -khtml-border-radius-bottomright:6px;
                       -khtml-border-radius-topright:6px;
                       -moz-box-shadow:0px 0px 4px #000;
                       -webkit-box-shadow:0px 0px 4px #000;
                       -khtml-box-shadow:0px 0px 4px #000;
                       background-color:#C6CF6B;
                       bottom:22px;
                       color:#000000;
                       font-weight:bold;
                       left:8px;
                       padding:6px;
                       position:absolute;
            }
            #amount{font-size: 14px;text-shadow:0px 1px 0px #ccc}
        </style>
    </head>

    <body>
        <div id="wrapper">
            <div class="left" id="leftSlider">
                <div id="range">Price Range <span id="amount"></span></div>
                <div id="slider"></div>
            </div>
            <div class="left" id="products">
                <?php
                echo showProducts();
                ?>
            </div>
        </div>

    </body>
</html>

Adding Ajax

Now we need to load the data from database and records should match our slider’s value, for this we will use “stop” event of slider component. This event is triggered when the user stops sliding.

$slider.slider({
                    range: true, // necessary for creating a range slider
                    min: <?php echo $minValue;?>, // minimum range of slider
                    max: <?php echo $maxValue;?>, //maximimum range of slider
                    values: [<?php echo $minValue;?>, <?php echo $maxValue?>], //initial range of slider
                    slide: function(event, ui) { // This event is triggered on every mouse move during slide.
                        $amount.html('$' + ui.values[0] + ' - $' + ui.values[1]);//set value of  amount span to current slider values
                    },
                    stop: function(event, ui){

                    }
                });

Now create one more file of name “ajaxSlider.php” and paste the following code in it

<?php
include 'slider.php';
$minValue = (int)$_GET['minValue'];
$maxValue = (int)$_GET['maxValue'];
if($minValue!=''&&$maxValue!='') {
    $where = "price >= $minValue and price <= $maxValue ";
    echo showProducts($where);
}
?>

Open your index.php file and update the slider component code like as follows

  $(function() {
                $slider = $("#slider");//Caching slider object
                $amount = $("#amount");//Caching amount object
                $products = $('#products');//Caching product object
                $ajaxMessage =  $('#ajaxMessage');//Caching ajaxMessage object

                $slider.slider({
                    range: true, // necessary for creating a range slider
                    min: <?php echo $minValue;?>, // minimum range of slider
                    max: <?php echo $maxValue;?>, //maximimum range of slider
                    values: [<?php echo $minValue;?>, <?php echo $maxValue?>], //initial range of slider
                    slide: function(event, ui) { // This event is triggered on every mouse move during slide.
                        $amount.html('$' + ui.values[0] + ' - $' + ui.values[1]);//set value of  amount span to current slider values
                    },
                    stop: function(event, ui){//This event is triggered when the user stops sliding.
                        $ajaxMessage.css({display:'block'});
                        $products.find('ul').css({opacity:.2});
                        $products.load('ajaxSlider.php?minValue='+ui.values[0]+'&maxValue='+ui.values[1],'',function(){
                            $ajaxMessage.css({display:'none'});
                        });
                    }
                });

                $amount.html('$' + $slider.slider("values", 0) + ' - $' + $slider.slider("values", 1));
            });

That’s it guys :)

sourcedemo


  • Safdar
    Thank you very much but i've a question if i entered a complex values like (1,2,3,5,15,20,25,50,100) i controlled all over with array but when i stored the values of slider and next given page cannot be get stored values
  • Visitor
    Thank you VERY VERY MUCH!!!
  • Sjeena
    Great, how can I implement it in oxid or ocsommerce ?
  • make changes in showProducts function so that it can fetch data from osCommerce product table
  • Sjeena
    Thank you.

    But what`s about oxid eshop? Because of the structure (OOP) I need help.
  • Thanks for this great piece of code! I am hoping to integrate this into a Joomla/VitueMart site I am working on.

    Will keep you updated on my progress ;)
  • Kemiga
    Could it be possible to get this working with joomla 1.5.17 / virtuemart 1.1.4 ?
    And could you give me some hints, what to grab in the database?

    By the way, it could be cool to build a module for joomla 1.5 for this awesome ajax price feature..
    I'm a newbie if we are talking about building modules for joomla.. I'll get there one day!

    Hands up for mypaaji
  • well ya it is possible but i am not able to find any free time now a days, just install virtuemart on your localsystem and check what tables being added in the database. You can fetch data from those tables.
  • Thomas
    AMAZING tutorial! You honestly made my day!

    Thnx!
  • Thanks for with gallary i am using this gallary in my website Nightlifeblues
  • Sandip
    hey hi....
    nice sample.....
    if i want 2 use same slider 2-3 times in one page...than wt 2 do.....

    Thanx............
  • Sabeen
    arey wah shehzade. such an interesting thing.
blog comments powered by Disqus