Sunday, 26 March 2017

load more div when click on button using jquery

display more divs when clicking button jquery
Description:

In this example we explain that how to display more Divs when clicking on button using jQuery.or jQuery load first 3 elements(divs) and then when click on l”oad more” button to display next 3 elements (divs) using jQuery.

Sometimes we have requirement like display only first 3 news in our homepage and if user click on load more news button then it will again load next 3 news because of load on server we only display required news at a time using jQuery clientside.

So below is the code that demonstrate load more elements when click on button using jQuery.
Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style type="text/css">
        .newsPreview
        {
            display: none;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            totalnews = $('#newsitem .newsPreview').length;
            x = 3;
            $('#newsitem .newsPreview').slice(0, 3).show();
            $('#loadMore').click(function () {
                alert("ca");
                if (x + 3 >= totalnews) {
                    $('#loadMore').hide();
                }
                x = (x + 3 <= totalnews) ? x + 3 : totalnews;
                $('#newsitem .newsPreview').hide();
                $('#newsitem .newsPreview').slice(0, x).show();
            });
            $('#showLess').click(function () {
                x = (x - 3 < 0) ? 3 : x - 3;
                $('#newsitem .newsPreview').slice(x).hide();
            });

        });
    </script>
</head>
<body>
    <strong>News</strong>
    <div id="newsitem" class="news-items">
        <div id="newsPreview" class="newsPreview">
            div 1</div>
        <div id="newsPreview" class="newsPreview">
            div 2</div>
        <div id="newsPreview" class="newsPreview">
            div 3</div>
        <div id="newsPreview" class="newsPreview">
            div 4</div>
        <div id="newsPreview" class="newsPreview">
            div 5</div>
        <div id="newsPreview" class="newsPreview">
            div 6</div>
        <div id="newsPreview" class="newsPreview">
            div 7</div>
    </div>
    <div id="loadMore">
        Load more</div>
</body>
<div id="showLess">
    Show less</div>
</html>



4 comments:

  1. thanks. also keep visiting updated post on blog.

    ReplyDelete
  2. thanks. also keep visiting updated post on blog.

    ReplyDelete
  3. thanks. also keep visiting updated post on blog.

    ReplyDelete
  4. thanks. also keep visiting updated post on blog.

    ReplyDelete