Click to reveal additional images once the "show more" button is pressed

Hey there! I'm currently working on implementing a feature where, upon clicking "show more", 3 images will be displayed. And if the user clicks again, another set of 3 images will appear, and so on. I seem to be facing some difficulties with the JavaScript part of it. Any help in identifying the error would be greatly appreciated.

You can find my code on fiddle here

$(document).ready(function () {
                image_x = $(".handler .col-md-4").size();
                x=1;
                $('.handler .col-md-4:lt('+x+')').show();
                $('#loadMore').click(function () {
                    x= (x+5 <= image_x) ? x+1 : image_x;
                    $('.handler .col-md-4:lt('+x+')').show();
                });
                $('#showLess').click(function () {
                    x=(x-5<0) ? 3 : x-5;
                    $('.handler .col-md-4').not(':lt('+x+')').hide();
                });
            });
.col-md-4 {
                width: 100%;
                text-align: center;
            }
            .col-md-6 {
                width: 100%;
                text-align: center;
            }
            #loadmore {

             border: 1px solid;
             padding: 20px;
            }
            #loadless {

             border: 1px solid;
             padding: 20px;
            }
<div class="handler">
            <div class="col-md-4">
               <div class="livery-article">
                  <a href="/blogs/good-company/72810435-hello-america">
                     <img class="livery-article-image"
                          src="http://cdn.shopify.com/s/files/1/0893/1740/files/blog1_large.png?16108356891554572192">
                  </a>
               </div>  
            </div>
            <br />
            <div class="col-md-4">
               <div class="livery-article">
                  <a href="/blogs/good-company/72810435-hello-america">
                     <img class="livery-article-image"
                          src="http://cdn.shopify.com/s/files/1/0893/1740/files/blog1_large.png?16108356891554572192">
                  </a>
               </div>  
            </div>
            <br />
            <div class="col-md-4">
               <div class="livery-article">
                  <a href="/blogs/good-company/72810435-hello-america">
                     <img class="livery-article-image"
                          src="http://cdn.shopify.com/s/files/1/0893/1740/files/blog1_large.png?16108356891554572192">
                  </a>
               </div>  
            </div>
            <br />
            <div class="col-md-4">
               <div class="livery-article">
                  <a href="/blogs/good-company/72810435-hello-america">
                     <img class="livery-article-image"
                          src="http://cdn.shopify.com/s/files/1/0893/1740/files/blog1_large.png?16108356891554572192">
                  </a>
               </div>  
            </div>
            <br />
            </div>
                
                <br />
                <br />
                <div class="col-md-6">
                    <a href="#" id="loadmore">show more image</a>
                    <a href="#" id="loadless">show more image</a>
                </div>
                <br />
                <br />
                <br />
                <br />
                <br />
                <br />

Answer №1

The code needed some minor adjustments. The id used in the HTML and jQuery were not aligned properly. I have made changes to update displays by toggling the CSS display.

$(document).ready(function () {
   x=1;
   $('.handler li:lt('+x+')').css('display','block');
   $('.handler li').not(':lt('+x+')').css('display','none');
});
$('#loadMore').click(function () {
   image_x = $(".handler li").size();
   x= (x+1 <= image_x) ? x+1 : image_x;
   $('.handler li:lt('+x+')').css('display','block');
});
$('#loadLess').click(function () {
   image_x = $(".handler li").size();
   x=(x-1<=0) ? 3 : x-1;
   $('.handler li').not(':lt('+x+')').css('display','none');
});

For more information, please check out: http://fiddle.jshell.net/n8f983cb/7/

Answer №2

Check out the revised code

After reviewing your code, I noticed several logic problems and typos in class names.

Therefore, I made some adjustments to your code. Please see if these changes meet your requirements.

Appreciate the opportunity to help (:

Answer №3

Although there were some mistakes in your code, such as using incorrect id's and other issues, I won't dwell on the minor typos and syntax errors that may not be useful knowledge for others in the future. Instead, I will show you my approach to solving the problem.

I recommend creating an object that contains a function for each action.

  • The showMore function should increment the counter and display the appropriate items.
  • The showLess function should decrement the counter and hide the appropriate items.

Create a single function that shows or hides items based on the counter value, and shows or hides each action depending on whether it can be used or not. Call this function at the end of each action defined earlier.

Add a delegated event listener to the parent element of the controls, find the correct function based on the id, and execute it. I included a fallback in case the code changes and can no longer locate the correct function.

I've simplified the HTML and utilized placeholder images to reduce the size of the demo below. However, it is compatible with your original HTML structure.

$(document).ready(function() {
    var images = $(".handler > div").hide(), x = 1;
    var showMore = $('#showMore');
    var showLess = $('#showLess');
    var funcs = {
       'showMore': function() { ++x; show(); },
       'showLess': function() { --x; show(); }
    }
    $('.controls').on('click', 'a', function(e){
        return (funcs[e.target.id] || function(){})(), false;
    });
    function show() {
        images.hide().filter(function(i){ return i < (x * 3); }).show();
        showMore.show().filter(function(){ return !images.is(':hidden'); }).hide();
        showLess.show().filter(function(){ return x === 1; }).hide();
    }
    show();
});
.handler { width: 600px; } .handler > div { display: inline-block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="handler"><div class="col-md-4"><div class="livery-article"><img src="//lorempixel.com/200/100/abstract"></div></div><div class="col-md-4"><div class="livery-article"><img src="//lorempixel.com/200/100/business"></div></div><div class="col-md-4"><div class="livery-article"><img src="//lorempixel.com/200/100/animals"></div></div><div class="col-md-4"><div class="livery-article"><img src="//lorempixel.com/200/100/cats"></div></div><div class="col-md-4"><div class="livery-article"><img src="//lorempixel.com/200/100/transportation"></div></div><div class="col-md-4"><div class="livery-article"><img src="//lorempixel.com/200/100/sports"></div></div><div class="col-md-4"><div class="livery-article"><img src="//lorempixel.com/200/100/cats"></div></div><div class="col-md-4"><div class="livery-article"><img src="//lorempixel.com/200/100/animals"></div></div></div><br /><div class="col-md-6 controls"><a href="#" id="showMore">show more images</a> <a href="#" id="showLess">show less images</a></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Sequelize to Create/Post Data with Many-to-Many Relationship

I've been exploring how to implement a M:N Association using Sequelize. After examining the documentation (doc), I came across a solution that closely matches my requirements: User.belongsToMany(Profile, { through: User_Profile }); Profile.belongsToMa ...

Why is the PHP response always 0 even though AJAX JSON data is being sent correctly during Wordpress plugin development?

There seems to be a simple issue here that I'm missing. The data is being sent correctly according to Firebug in the NET tab (NET tab-> Post -> Parameters). However, the PHP function does not even echo simple text. This is the PHP code: add_ac ...

Is there a way to add a dynamic animation of steam rising from a coffee cup to my SVG icon design?

I'm a budding graphic designer eager to master the art of SVG animated icons and coding. Recently, I created an SVG file of a beautiful cup of coffee using Illustrator and now I want to make the steam rise realistically through animation. However, des ...

jQuery error: an unexpected token was encountered

I am encountering an issue with an "unexpected token =" error on the line toggleNav = function(evt){ in the code snippet below. Despite going through various similar posts, I am unable to pinpoint why this error is occurring. Any assistance in guiding me ...

Difficulty encountered when choosing and interacting with website button with the utilization of Python 3.5.1 and Selenium 2.53.2

I am currently utilizing a Macbook Air that runs on OS X El Capitan. My tool of choice is Python IDLE, and I am attempting to target and interact with the button located on the webpage below: <div class="search-form-actions"> <button class="btn ...

Exploring the elimination of box shadow on elements that overlap

view image hereI'm experiencing an issue with my HTML code where a box shadow appears in the mobile view. Despite my efforts, I cannot seem to remove it. This problem only arises in the mobile view, leading me to believe that it may be related to how ...

Tips for getting a jQuery click event to function properly within an AngularJS application

Although I have some experience with jQuery and can write basic jQuery code, I am currently learning AngularJS. I have been following tutorials and studying sample code. Now, I want to practice some basic tasks in Angular that I could easily do with jQuer ...

Having trouble with jQuery and Ajax POST requests

I designed a basic html page and utilized jquery/ajax to transmit a simple json file to my php server. The behavior of my code is quite puzzling. Initially, I followed suggestions from other Stack Overflow queries: Script1 var data = {"deviceUUID":"ab ...

Animating the opacity of elements using jQuery and CSS

Trying to put together a fading slideshow with five slides that will loop back to the beginning. My code seems like it should do the trick, but there's something not quite right. <script type="text/javascript"> $(document).ready(function( ...

Managing the response from a dataless AJAX GET request

I find myself stuck on a seemingly simple issue. I am currently working on refining a basic AJAX GET request function that deals with response handling. There is no data being sent out with the request; instead, the data is managed through the GET URL. Whi ...

Add transparency to a component using CSS

I am currently facing an issue with a div element called signup-box. I have applied an opacity value of 0.65 to it, but unfortunately, this is affecting everything within the div as well. This means that my white text is no longer visible as white and th ...

Enzyme fails to locate text within a div even though it is present

In my current test scenario, I have a set of data displayed in Material-UI Cards. The data is provided through a JSON array consisting of objects with fields like projectName, crc, dateCreated, createdBy, and lastModified. { projectName: 'P ...

Creating a private variable to perform a select_sum query

I have defined private variables in my CodeIgniter code like this: private $table = 'phone'; private $column_order = array(null, 'name', 'price'); private $type = array('type'); private $battery_consumption = array ...

Incorporating Entrance Animations for Individual Elements within ngView Using AngularJS

Can each content within ngView be animated individually upon entering, rather than the entire View (div) itself? ...

Using a Button component as a TableCell in a material-ui Table

Hey there! I'm looking for some assistance in adding buttons as TableRowColumns in the material-ui Table. I'm working on implementing an approval system to approve or reject user requests, and I thought presenting them in a tabular format would b ...

Utilize TypeScript functions within Angular applications

I have successfully created a TypeScript module and after compiling it, I am generating a JavaScript file. However, when I try to use this JavaScript file within my Angular project in the index.html, it loads but I cannot access its functionality from any ...

Solving the CSS Trick: Responsive Data Table (featuring inline editing) Display Glitch

In my quest to create a responsive table with inline editing, I turned to Chris's guide at CSS-Tricks (check it out here). To see how it all comes together, take a look at this Plunker demo. On mobile screens, the responsiveness is on point. https: ...

Gleaming R: Warning prompt or modal box input: invalid

In the process of developing a basic application, I am seeking to implement a pop-up notification for invalid inputs. By referencing the suggestion provided in #1656, I have come up with an example that introduces a visually appealing background color when ...

Manipulate Nested Objects using an Array of Keys

Currently, I am developing a recursive form using React and MUI that is based on a nested object. Throughout this process, it is crucial for me to keep track of the previous keys as I traverse through the recursion. As users interact with the form and mak ...

What is the best way to apply overlays to customize a specific part of a single character while also accommodating dynamic width adjustments?

Query Is it feasible to style a specific portion of a single character? Interpretation You cannot apply CSS attributes to parts of characters. However, if you wish to style only a particular section of a character, there is currently no standardized met ...