Conceal the "Load More" buttons in Ruby on Rails once all items have been displayed

Currently, I am in the process of integrating the Load More button into a Ruby on Rails application. The implementation has been successful so far. However, there is an issue where the Load More button continues to appear even when there are no more photos left to be displayed.

Below are the code snippets:

<div class='container'>
        <div class='section-header'>
            <h2> Let's Rewind! </h2>
        </div>
        <div class='row'>
            <div class='container'>
                <div class='cust-cont'>
                    <%= render @scroll_photos %>
                </div>
            </div>
        </div>
        <div class="load-more-container">
            <%= image_tag "ajax-loader.gif", style: "display:none;", class: "loading-gif" %>
            <%= link_to "Load More", scroll_photos_path, class: "load-more" %>
        </div>
    </div>

_scroll_photo.html.erb

<div class="col-lg-12 col-md-4 col-xs-12">
  <div class="image-box-4-3">
        <div class="record" data-year="<%= scroll_photo.year %>">
            <div class="image-content">
                <%= image_tag(scroll_photo.image_link, width: "100%") %>
            </div>
        </div>
    </div>
  </div>

And here's the controller:

if params[:year]
      # get all records with id less than 'our last id'
      # and limit the results to 5
      @scroll_photos = ScrollPhoto.where('year < ?', params[:year]).limit(2)
    else
      @scroll_photos = ScrollPhoto.limit(2)
    end
    respond_to do |format|
      format.html
      format.js
    end

Javascript for handling the Load More functionality:

$(document).ready(function(){
    // when the load more link is clicked
    $('a.load-more').click(function(e){

      // prevent default click action
      e.preventDefault();

          // hide load more link
          $('.load-more').hide();

          // show loading gif
          $('.loading-gif').show();

      // get the last id and save it in a variable 'last-id'
          var last_year = $('.record').last().attr('data-year');

          // make an ajax call passing along our last user id
          $.ajax({

              type: "GET",
              url: $(this).attr('year'),
              data: { year: last_year },
              dataType: "script",

              success: function(){
                  $('.loading-gif').hide();
                  $('.load-more').show();
              }

          });

    });
  });

index.js.erb

$('.cust-cont').append('<%= escape_javascript(render(:partial => @scroll_photos)) %>')

Answer №1

To eliminate the load more section, simply use the following code in your controller action: @scroll_photos

# Insert this into your javascript file

<% if @scroll_photos.empty? %>
  $('.load-more-container').hide()
<% else %>
  $('.cust-cont').append('<%= escape_javascript(render(:partial => @scroll_photos)) %>')
<% end %>


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

Showing the outcome of a PHP function within a div container

While working on my WordPress site, I've implemented user registration and login functionality. However, I'm not a fan of the default 'admin bar' and would rather create a custom navigation bar. I am looking for a way to dynamically loa ...

Unable to adjust the padding of the material UI Select component

I'm having trouble adjusting the padding of the Select component in order to align it with the size of my other text fields. Despite knowing that I need to make changes to nested components, I have yet to discover a viable solution. <div className ...

Creating a dynamic image display feature using VueJS

Explore the connections between the elements How can I transmit a value from one child component to another in VueJS? The code snippet below is not generating any errors and the image is not being displayed <img v-bind:src="image_url" /> Code: & ...

Run JavaScript function when an ajax request encounters an error

When using the ajax function to call a webservice and encountering an error, my goal is to trigger the userCreate() javascript function. $.ajax({ type:"POST", beforeSend: function (request) { request.setRequestHeader("X-DreamFactory-Applic ...

Retrieve all objects of the selected value using Angular autocomplete when an option is selected

I am currently working with an autocomplete component. I am passing an array of objects and would like to retrieve all item information (option) when an option is selected, not just the field value (option.name). <form class="example-form"> ...

Discovering the closest date among the elements in an array

Currently, I am facing an issue while trying to identify the highest date within an array of objects which have varying dates assigned to each one. The code seems to be functioning well when the dates are above January 1st, 1970, however, any date prior to ...

Discovering the function invoker when in strict mode

I am facing a challenge in my Angular controller where I have a function called getGames() that can be triggered by both the init() and update() functions. The issue is, I need to handle these two scenarios differently based on which function called getGam ...

Displaying search results in various Angular components

On my home page (homePageComponent), I have a search feature. When the user clicks on the search button, they are redirected to a different page called the search list page (searchListComponent). Within the searchListComponent, there is another component c ...

How can I convert the date format from ngbDatepicker to a string in the onSubmit() function of a form

I'm facing an issue with converting the date format from ngbDatepicker to a string before sending the data to my backend API. The API only accepts dates in string format, so I attempted to convert it using submittedData.MaturityDate.toString(); and su ...

Encountering errors with passport-google-oauth20: InternalOAuthError arises when fetching user profile fails and attempting to set headers after they have already been sent to the client

When using passport strategies for various social media logins, I encountered the following two errors: InternalOAuthError: Failed to fetch user profile Cannot set headers after they are sent to the client I suspect that I may have returned a callback or ...

Determining a User's Connection Status in ReactJS: Cellular Network or WiFi?

Are there any tools or applications available that can determine if a user is connected to WiFi or using a cellular network? ...

How can I prevent anchors from performing any action when clicked in React?

My dilemma involves this HTML element: <a href onClick={() => fields.push()}>Add Email</a> The purpose of the href attribute is to apply Bootstrap styles for link styling (color, cursor). The issue arises when clicking on the element caus ...

Evaluating the criteria and presenting two distinct notifications with setCustomValidity

When validating text fields in an HTML form, I am looking to check two conditions. Currently, the code below checks if the phone number entered is in the correct format and displays a message 'Enter a valid mobile number' if it is incorrect using ...

Angular 2 - Module 'ng-factory' not found

I am encountering an issue when trying to launch my clean UI theme using 'ng serve'. This is my first time working with Angular and I'm struggling to resolve this problem. Any assistance would be greatly appreciated. I have attempted re-inst ...

What could be causing the data storage issue in the state?

Using axios, I am fetching data and storing it in a state variable useEffect(() => { getCartItems(); }, []); const [abc, setAbc] = useState([]); const getCartItems = async () => { let data = await CartApi.get(`/${store.getState().auth.user.id}/ ...

The process of parsing HashMap failed due to an unexpected encounter with an Array, when an Object

Currently, I am in the experimental phase of creating an action at Hasura using a Node.js code snippet hosted on glitch.com. The code snippet is as follows: const execute = async (gql_query, variables) => { const fetchResponse = await fetch( "http ...

Is it possible to load textures in Three.js and Cordova without relying on a server or HTTP?

I am currently working on developing a Cordova game using Three.js with the goal of making it playable offline. However, I have encountered an issue where Three.js requires texture files to be served via HTTP, making it challenging to achieve offline funct ...

An abundance of AJAX requests inundating the server

While working on a straightforward AJAX request, I encountered an issue where the server is sending back 3 responses instead of just one (you can see the example in the attached image). Could someone provide insight into why this might be happening? var ...

Utilizing AJAX to locate a phone number

I am seeking guidance on how to utilize AJAX to search for phone numbers using a search box. Below is the code corresponding to this matter. <script type="text/javascript"> $(document).ready(function($){ $('#query').keyup(function(){ ...

Advanced manipulation of scope in JavaScript

In order to ensure scope-busting for a specific listener in my application, I have implemented the following code: // within the prototype of MyClass var self = this; myElement.addEventListener("stuff", function(e){self.doStuff(e)}); By doing this, I am ...