Prevent the upward arrow from appearing on the first row and the downward arrow from appearing on the last row when

This is a straightforward question, but I'm unsure how to achieve it.

I am currently working on sorting columns using jQuery.

$(document).ready(function(){
    $(".up,.down,.top,.bottom").click(function(){
        var row = $(this).parents("tr:first");
        if ($(this).is(".up")) {
            row.insertBefore(row.prev());
        } else if ($(this).is(".down")) {
            row.insertAfter(row.next());
        } else if ($(this).is(".top")) {
            //row.insertAfter($("table tr:first"));
            row.insertBefore($("table tr:first"));
        }else {
            row.insertAfter($("table tr:last"));
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
    <tr>
        <td>One</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr>
        <td>Two</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr>
        <td>Three</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr>
        <td>Four</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr>
        <td>Five</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
</table>

Now I need to :

  1. Disable "Up" on the first row
  2. Disable "Down" on the last row

This will always disable the first and last rows even if I move another row to the first or last position.

Answer №1

Can you achieve this effect with just CSS and capturing the rowIndex value using a keyboard return?

const tableTbody = document.querySelector('table tbody')
  ,   FirstUp    = tableTbody.querySelector('tr:first-of-type').rowIndex
  ,   LastDown   = tableTbody.querySelector('tr:last-of-type').rowIndex
  ;
tableTbody.onclick = e =>
  {
  if (!e.target.matches('a[data-mv]')) return

  let rIndex = e.target.closest('tr').rowIndex

  switch (e.target.dataset.mv)
    {
    case 'up':
      if (rIndex != FirstUp)
        tableTbody.insertBefore(tableTbody.rows[rIndex], tableTbody.rows[rIndex-1])
      break
    case 'down':
      if (rIndex != LastDown)
        tableTbody.insertBefore(tableTbody.rows[rIndex+1], tableTbody.rows[rIndex])
      break
    }
  }
#myTable tbody tr:first-of-type a[data-mv=up],
#myTable tbody tr:last-of-type  a[data-mv=down] {
  cursor          : not-allowed;
  pointer-events  : none;
  opacity         : 0.5;
  text-decoration : none;
}
<table id="myTable">
  <tbody>
    <tr>
      <td>One</td>
      <td> <a href="#" data-mv="up">Up</a> <a href="#" data-mv="down">Down</a> </td>
    </tr>
    <tr>
      <td>Two</td>
      <td> <a href="#" data-mv="up">Up</a> <a href="#" data-mv="down">Down</a> </td>
    </tr>
    <tr>
      <td>Three</td>
      <td> <a href="#" data-mv="up">Up</a> <a href="#" data-mv="down">Down</a> </td>
    </tr>
    <tr>
      <td>Four</td>
      <td> <a href="#" data-mv="up">Up</a> <a href="#" data-mv="down">Down</a> </td>
    </tr>
    <tr>
      <td>Five</td>
      <td> <a href="#" data-mv="up">Up</a> <a href="#" data-mv="down">Down</a> </td>
    </tr>
  </tbody>
</table>

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

Executing JavaScript code within a Django application to load a file

Utilizing a JavaScript tool called jQuery FileTree within my Django application has presented a dilemma. This particular JavaScript requires access to a python script path, but incorporating Django template tags directly into JavaScript poses an issue. Wi ...

Neither req.body nor req.file contain any data

Hey everyone, I'm new to coding and currently working on creating a basic markdown blog. However, I'm facing an issue where req.body doesn't contain my markdown field and req.file is undefined when trying to upload an article. I'm unsur ...

Loading animation reminiscent of a whirlpool, similar to the movement

In my quest for the perfect animation, I have scoured far and wide. Unfortunately, the one I found at http://jsfiddle.net/pedox/yed68/embedded/result/ is created using css, which many browsers do not yet support fully. I also explored , but found it to be ...

What is the process for linking read-only methods to Redux object instances?

Let's say I have a "user" object stored in redux, with fields for first name and last name (interface User { firstName : string, lastName : string} if using typescript). After retrieving a user from redux, I want to obtain the full name of the user by ...

What is the process for including a custom Jasmine matcher definition in Typescript?

I've been searching around for information on creating custom Jasmine matchers using TypeScript and it seems like a common issue. However, none of the solutions I've come across have worked for me. My setup includes: { "typescript": "2.3.2", ...

Using the i18next Module for Localization in ExpressJS and Front-End Development

I am currently integrating the i18next module into my NodeJs/ExpressJS web application. All the translation files are stored in the /locales directory. According to information from i18next.com, it can also be utilized on the client side. <script typ ...

Creating dynamic keys to insert objects

In my coding project, I am dealing with an empty array, a value, and an object. Since there are multiple objects involved, I want to organize them into categories. Here is an example of what I envision: ARRAY KEY OBJECT OBJECT KEY OBJECT ...

"Why is it that the keypress event doesn't function properly when using the on() method

My goal is to capture the enter event for an input field $("input[name='search']").on("keypress", function(e){ if (e.which == '13') { alert('code'); } }); This is the HTML code snippet: <input name="searc ...

Cloudflare SSL Error 522 Express: Troubleshooting Tips for Res

After setting up my express project using express-generator, I decided to make it work with a cloudflare SSL Certificate for secure browsing over https. My express app is running on port 443. Despite my efforts, when I try to access the domain, I encount ...

Pair a specific portion of text with another string

I'm having trouble finding a substring within a string. The substring and the string are as follows: var str="My name is foo.I have bag(s)" var substr="I have bag(s)" When I use str.match(substr), it returns null, probably because the match() funct ...

Create a duplicate of the table and remove specific rows

Hi there, I have a query about duplicating a table. I am looking to extract specific results and display only those results. To illustrate, here is an example in HTML code: <table class="table table-striped" id="ProfileList2"> <tbody> ...

The NoUiSlider had already been initialized

Currently, I am facing an issue when trying to incorporate noUiSlider with Angular JS. I have a directive that contains 4 sliders and I intend to display this directive on 2 different pages. However, each time I switch between the pages, an error occurs st ...

Creating a file solely for route definitions and then employing them within index.js

My index.js file contains the following routes: import { createRouter, createWebHistory } from '@ionic/vue-router'; import { RouteRecordRaw } from 'vue-router'; const routes = [{ path: '', redirect ...

How can I implement a loop using .then in JavaScript?

Looking to understand the .then concept in JavaScript, I am curious if it is feasible to generate a series of .then's using a for loop. request.send(myRequest) .then(r => console.log(r, 0)) .then(r => console.log(r, 1)) .then(r => ...

Retrieve the height and width of all images within a specified directory using PHP

I'm currently working on an image directory in PHP, and I require the height and width of images in PHP to be used in HTML. I attempted to use JavaScript but it didn't provide the accurate values for the image's height and width. Can you sug ...

Using Vuejs to dynamically render raw HTML links as <router-link> elements

Hey there, I'm just getting started with VueJS and I've been doing some interesting experiments. I created a backend service using Python/Flask that provides me with a string of HTML code containing many tags. My goal is to render this HTML insid ...

Is there a way to access hover effect information in Atom editor similar to how it appears in VScode?

Is there a specific plugin required in Atom to display information when hovering over variables, objects, or functions similar to intellisense? VSCode does this automatically, but I am looking for the same functionality in Atom. https://i.stack.imgur.com/ ...

What is the best way to obtain the current cursor location in draft.js?

As part of my draftjs project, I'm working on implementing a feature that allows users to easily insert links. One approach I've taken is creating a popup that appears when the shortcut cmk + k is pressed. To enhance the user experience, I am cu ...

The knockout.js subscribe function isn't activating during the initial set

In my model class, I have defined observables and I am looking to subscribe to their sets. Below is the code snippet that showcases what I currently have: var dto = function (data) { var self = this; self.Value1 = ko.observable(data.Value1); s ...

Setting a custom tab as the default route in Expo Router without relying on an index.tsx file - here's how!

In the development of my React Native app using Expo Router, I am structuring it into main sections with a tabs layout consisting of Events, Search, and Profile. Here is an image showcasing the desired folder structure: The main sections Events, Search, ...