Choosing a specific category to display in a list format with a load more button for easier navigation

Things were supposed to be straightforward, but unexpected behaviors are popping up all over the place!

I have a structured list like this

XHTML

<ul class = "query-list">
    <li class="query"> something </li> 
    <li class="query"> something </li>
    <li class="query"> something </li>
    <li class="query"> something </li>
    <li class="query"> something </li> //Should this actually be li:last-child?
    <a class="fetch-more" href="#">Fetch More</a>
</ul>

The list displays 5 posts initially, then loads another 5 when a.fetch-more is clicked until all posts are loaded. Once all posts are retrieved, a.fetch-more disappears. This is the default DOM rendering.

JAVASCRIPT

Template.bar.onRendered( function() {
$(document).keydown(function(e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode == 74) { //Keydown J
        var listItem = $('ul.query-list > li.query');
        var listItemFirst = $('ul.query-list > li.query:first-child');
        var selectedChild =  $('ul.query-list > li.query.selected-child');

        if($('input').is(":focus")|| $('textarea').is(":focus")){
            return null; //Prevent activation when input or textarea is focused
        } else {
            e.preventDefault();
            if(! $(listItem).hasClass('selected-child')){
                $(listItemFirst).addClass('selected-child'); //Select first child if ul > li has no selected items
            } else
            if( $(listItemFirst).hasClass('selected-child')) {
                $(listItemFirst).removeClass('selected-child');
                $('ul.query-list > li.query:last-child').addClass('selected-child'); //If first child is selected, select last child
            } else { 
                selectedChild.removeClass('selected-child');
                selectedChild.prev().addClass('selected-child');  // If none of the above applies, select previous li
            }
        }
    }
});
});

The JS performs as intended.

However, there are some issues that I'm facing.

  • Upon navigating away and returning, the order of li selection is incorrect. (i.e., selected in the sequence of second, fourth, third, one. Resolved upon refresh)
  • If more posts need to be loaded, the last child will not select.

UPDATE 1

Problem 2 has been resolved (Thank you @Fabrizio Calderan). I moved the a.fetch_more outside the ul. Yet, upon navigation back, the selection order is still jumbled.

Answer №1

To start, remove the "Load More" link from the UL element. A UL should only have LI elements inside.

Next, in the keydown handler function, consider following these steps for simplicity:

  • Identify the currently selected LI element and remove the "selected-child" className from it
  • Determine the index of the LI element you wish to select
  • Add the "selected-child" className to the LI element with the calculated index
Template.foo.onRendered(function() {
    $(document).keydown(function(e) {
        var keyCode = e.keyCode || e.which,
            c = 'selected-child',
            $listItems, $selected, index;
        if (keyCode == 74) { //Key down J
            if ($('input').is(":focus") || $('textarea').is(":focus")) {
                return;
            } else {
                $listItems = $('.question-list li');
                $selected = $listItems.filter('.' + c).removeClass(c);

                // *** Navigate backwards through the list ***
                index = ($selected.length == 0) ? 0 : $selected.index() - 1;
                if (index < 0) 
                    index = $listItems.length - 1;

                // *** Navigate forwards through the list ***
                // index = ($selected.index() + 1) % $listItems.length;

                $listItems.eq(index).addClass(c);
            }
        }
    });
});

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

JS animation triumphant

I have developed an app that utilizes a checkbox to control the appearance of an overlay on a screen. To ensure smooth transitions, I have incorporated animations into the process. #overlay{ position:absolute; height: 100vh; width: 100vw; ...

The necessary parameters are not provided for [Route: sender] with the [URI: {name}/{code}]. The missing parameters are name and code

I have encountered a problem while using AJAX and I am struggling to find a solution. Routes: web.php Route::get('/{name}/{code}', 'TestController@counter'); Route::post('/{name}/{code}', 'TestController@sender')-&g ...

Enhancing the smoothness of parallax scrolling

My header is going to be twice the height of the viewport. I added a simple parallax effect so that when you scroll down, it reveals the content below. However, I'm experiencing flickering in the content as I scroll, possibly due to the CSS style adju ...

What is the best way to incorporate animation using Tailwind CSS within my Next.js project?

I have a challenge with placing three images in a circular path one after the other using Tailwind CSS for styling. I've identified the circular path and keyframe style for the images. How do I configure this style in my Tailwind config file and imple ...

What steps do I need to take to build something similar to this using AngularJS?

Struggling with understanding the concepts of AngularJs. How can I create textfields and animations like the ones in this example using AngularJS? I've tried exploring directives, but it's not quite clicking for me. I've attempted to follow ...

What is the reason for npm and yarn to download multiple versions of jquery?

For the purpose of investigating how package managers like npm, yarn, and cnpm work in Node.js, I conducted an experiment. During the test, I came across two packages: jquery-dreamstream and jquery.tree. Both of them have a dependency solely on jquery wit ...

When using PHP's `json_encode()`, don't forget to append a "1" at the

While utilizing json_encode in my project, I have encountered an issue that is perplexing. On one particular page where I make an ajax call, the resulting json seems to mysteriously add a 1 to the end of the string. The output of my return string appears ...

Express.js returning unexpected results when calling MySQL stored procedures

I've encountered a strange issue with a stored procedure called getUsers in MYSQL. When I execute the procedure in phpmyadmin, it returns a table of users with their data perfectly fine. However, when I try to call the same procedure from my Node.js a ...

Modify a class attribute within a function

I need to modify the this.bar property within my class when a click event occurs. The issue is that the context of this inside the click function is different from the this of the class. export class Chart { constructor() { this.bar; } showC ...

Incorporating Blank Class into HTML Tag with Modernizr

Currently, I am experimenting with Modernizr for the first time and facing some challenges in adding a class to the HTML tag as per the documentation. To check compatibility for the CSS Object Fit property, I used Modernizr's build feature to create ...

Console displaying a 400 bad request error for an HTTP PUT request

I'm currently in the process of developing a react CRUD application using Strapi as the REST API. Everything is working smoothly with the GET, DELETE, and CREATE requests, but I encounter a 400 bad request error when attempting to make a PUT request. ...

Selenium: A guide to specifying CSS for webpages with multiple elements sharing the same name

Looking for assistance with CSS selection: <table id="userPlaylistTable" cellspacing="0" cellpadding="0"> <div class="numCellWrapper"> ... When defining a css selector, how can I target a specific element among multiple elements of the same ...

The display: flex property is not being properly implemented in Tailwind CSS for the sm:flex

I have a div with the following styles <div class="hidden sm:visible sm:flex"> .... </div> The sm:visible style is applied like this @media (min-width: 640px) .sm\:visible { visibility: visible; } However, the property disp ...

The retrieval of data from AWS Dynamodb in Node.js is not done synchronously

I recently started working with Node.js and DynamoDB. I created a Node.js SDK to retrieve a single row from a DynamoDB table. The data is being fetched correctly, but there is a delay which is causing an error. Below is a snippet of my code: var AWS = re ...

Modify anchor link color in a one-page website by using Jquery to detect scroll position changes when reaching different page sections

Each if statement contains specific numbers to change the text color of the visited/current/active anchor link. The height of the page is dependent on its width. How can this be resolved? Apologies if my explanation is confusing, English isn't my stro ...

JavaScript implementation of Ancient Egyptian Multiplication using PHP code

Let's dive into the algorithm. If we have two integers, A and B (remember, only integers), that need to be multiplied, here is how it works: we continuously multiply A by 2 and divide B by 2 until B cannot be divided any further, or in other words, un ...

Assistance with HTML and CSS to position an image in the corner

I need assistance with positioning a corner image on top of another image. I want the span, which has a small background image, to be in the top left corner of the main image. Below is my code: <div id="wrapkon"> <span style="width: 4px; height: ...

create new Exception( "Invalid syntax, expression not recognized: " msg );

Can someone assist me in identifying the issue at hand? Error: There seems to be a syntax error, and the expression #save_property_#{result.id} is unrecognized. throw new Error( "Syntax error, unrecognized expression: " msg ); Here is the c ...

By clicking the button, you can add an item to select2

Utilizing the select2 tag style in my Drupal YAML form allows users to easily locate and add various items. These items come with both images and titles on the same page, accompanied by a button next to each image. My goal is to enable users to click the b ...

ReserveYourSpot: Effortless Seat Reservation with AngularJS at the Click of a Button [GIF]

ReserveYourSpot: An innovative AngularJS application designed to streamline the process of reserving seats for a movie show, similar to popular platforms like BookMyShow. https://i.stack.imgur.com/PZk1I.gif Interactive User Functions (Use Cases): A ...