Skip to content

up-href in table row (tr) not working #489

@marc-mabe

Description

@marc-mabe

Bug description

up-href not working on table tr element.
I have a table which I want to make rows clickable.
This is not supported by plain HTML and because of that I read about up-href

[up-href]
Makes any element behave like a hyperlink.

Unfortunately this does not work so I still have to use a custom stimulus controller instead.

Reproduction project

https://shelled-terrific-waitress.glitch.me/

Steps to reproduce the behavior:

  1. Go to reproduction project linked above
  2. Click next to the links within the table row
  3. See mouse is pointer but nothing happens on click

Expected behavior

The table row should expect like a link the following the URL on click.

Browser version

  • OS: Linux
  • Browser Firefox
  • Version 113.0

Additional context

It works with my custom written stimulus controller:

<table>
<tr
    data-controller="anchor"
    data-anchor-href-value="./target"
>
    <td>whatever</td>
</tr>
</table>
import { Controller } from '@hotwired/stimulus';

/**
 * Handles any element like an anchor element
 * (follow link defined in href on click)
 *
 * This is useful for table rows (tr) to be clickable
 * as the tr-element is not allowed to be surrounded by an anchor element.
 */
export default class extends Controller {
    static values = {
        href: String,
    };

    declare hrefValue: string;

    onClick = (event: Event) => {
        // Do not follow link on selecting text within this anchor
        const selectedText = window.getSelection()?.toString();
        if (selectedText) {
            return;
        }

        // Do not follow link on clicking a sub anchor within this anchor
        // e.g. <tr data-contoller="anchor" ...><td><a href="#">test</a></td></tr>
        if (event.target instanceof HTMLElement) {
            const targetAnchor = event.target instanceof HTMLAnchorElement ? event.target : event.target.closest('a');

            if (targetAnchor && !targetAnchor.contains(this.element)) {
                return;
            }
        }

        window.location.href = this.hrefValue;
    };

    connect() {
        this.element.addEventListener('click', this.onClick);

        if (this.element instanceof HTMLElement) {
            this.element.style.cursor = 'pointer';
        }

        super.connect();
    }

    disconnect() {
        this.element.removeEventListener('click', this.onClick);
        super.disconnect();
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions