-1

I am trying to make every HTML element in my project clickable. When it is clicked, it should take me to another webpage (other.html) my JS:


let objs = document.querySelectorAll( 'body *' );
console.log(objs)
Array.from(objs).map(x => {
if (x.hasAttribute('loc') && x.hasAttribute('trig')){
let loc = x.getAttribute('loc')
let trig = x.getAttribute('trig')
let functionAtLast = function() {location.href = loc}
x.addEventListener(trig, functionAtLast)

}
})

my HTML:

<b loc = 'other.html' trig = 'click'>hi</b>

When I click on the bold text, nothing happens.

What am I doing wrong here?

4
  • "I am trying to make every HTML element in my project clickable" - why? That sounds like a bad idea because not every HTML element is interactable (e.g. <script> and <noscript>, <style>, etc)
    – Dai
    Dec 11, 2021 at 3:52
  • Custom attributes should be written with data-. See Using data attributes. Does nothing happen or do you receive an error? If the latter, what is the error? Dec 11, 2021 at 3:52
  • map is an FP-style function that returns a new array, it is not equivalent to forEach.
    – Dai
    Dec 11, 2021 at 3:53
  • You should change your selector to body *[log][trig].
    – Dai
    Dec 11, 2021 at 5:50

1 Answer 1

0

map should not be used to mutate array elements - nor is it intended to be used to iterate over an array. For that you should use for( of ) (don't use the .forEach method either).

  • You should use HTML5's data-* attributes for storing custom data instead of defining your own standard-looking attributes.
    • I assume trig is short for "trigger", which is a runtime-defined event-name.
    • I assume loc is short for "location", the href URI, basically. I've changed it to data-href.

Like so:

function setupClickableEverything() {
    const allBodyElementsWithAttribs = document.querySelectorAll( 'body *[data-event-name][data-href]' );
    for( const el of allBodyElementsWithAttribs ) {
        const eventName = el.dataset['eventName'];
        el.addEventListener( eventName, setWindowLocationToDataSetHref );
    }
}

window.addEventListener( 'DOMContentLoaded', setupClickableEverything );

function setWindowLocationToDataSetHref( e ) {
    
    const el   = e.currentTarget;
    const href = el.dataset['href'];
    window.location = href;
}

Example HTML:

<b data-href="https://stackoverflow.com/questions/51390971/im-lost-what-happened-to-asp-net-mvc-5/51391202#51391202" data-event-name="click">Navigate on click</b>
<br />
<b data-href="https://stackoverflow.com/questions/15305278/how-to-check-if-a-string-contains-a-specific-text/15305313#15305313" data-event-name="mousedown">Navigate on mousedown</b>
<br />
<b data-href="https://stackoverflow.com/questions/70011022/is-there-a-difference-between-and-is-not-in-c/70011062#70011062" data-event-name="contextmenu">Navigate on right-click</b>

Here's a slightly modified demo using a StackOverflow snippet. Due to SO's CSP imposed on Snippets the demo below cannot navigate-away, open a popup, or load content into an <iframe>, but it still demonstrates it working in principle:

function setupClickableEverything() {

    const allBodyElementsWithAttribs = document.querySelectorAll( 'body *[data-event-name][data-href]' );

    for( const el of allBodyElementsWithAttribs ) {
        
        const eventName = el.dataset['eventName'];
    //  const href      = el.dataset['href'];
        el.addEventListener( eventName, setWindowLocationToDataSetHref );
    }
}

window.addEventListener( 'DOMContentLoaded', setupClickableEverything );

function setWindowLocationToDataSetHref( e ) {
    
    const el   = e.currentTarget;
    const href = el.dataset['href'];
    //window.location = href;
    // To avoid breaking this demo, links are opened in the <iframe>.
    // StackOverflow snippets cannot use `window.open`.
    
//  document.getElementById('demoIFrame').src = href;
    document.getElementById('demoOutput').textContent = href;
}
<b data-href="https://stackoverflow.com/questions/51390971/im-lost-what-happened-to-asp-net-mvc-5/51391202#51391202" data-event-name="click">Navigate on click</b>

<br />

<b data-href="https://stackoverflow.com/questions/15305278/how-to-check-if-a-string-contains-a-specific-text/15305313#15305313" data-event-name="mousedown">Navigate on mousedown</b>

<br />

<b data-href="https://stackoverflow.com/questions/70011022/is-there-a-difference-between-and-is-not-in-c/70011062#70011062" data-event-name="contextmenu">Navigate on right-click</b>

<hr />

<!-- To avoid breaking this demo, links are NOT actually opened, just shown in the <output> element below. I tried to make it work using an <iframe> but the CSP on SO prevents that. Note that SO snippets are blocked from using `window.open` too.  -->
<!--<iframe id="demoIFrame" width="500" height="500" border="1"></iframe>-->
<output id="demoOutput"></output>

6
  • Minor nitpick: Isn’t the “event name” more commonly called the event type? Dec 11, 2021 at 6:04
  • 1
    @SebastianSimon You are technically correct (the best kind of correct) however in MDN's quasi-authoritative documentation they use the terms "name" and "type" interchangeably and given the OP seems new to JS and the DOM I wanted to use terms more easily-understood.
    – Dai
    Dec 11, 2021 at 6:07
  • I am trying this but it doesn’t work. No errors, but the when I click on the text, nothing happens. Dec 11, 2021 at 15:22
  • @JSst67 Did you use your debugger? Did you ensure the script only runs after DOMContentLoaded?
    – Dai
    Dec 11, 2021 at 15:23
  • @JSst67 I've updated my answer to contain a working example (albeit without actually navigating anywhere, due to security restrictions on SO snippets).
    – Dai
    Dec 11, 2021 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.