Removing inline JS

I want to remove inline JS in the following Codepen

I’m sure I don’t have to put an event listener on each <li> (there are 11 here but 78 on the real site).

But how? Do I need to use data attributes? Can I put a listener on the containing div and check which list item was clicked on?

The following code adds a click event listener to each anchor:

var links = document.querySelectorAll("#card-layout a");
links.forEach(function (link, i) {
  link.addEventListener("click", function () {
    choosecard(i);
    return false;
  });
});

That lets you remove the HTML inline event attribute from all of the links.

1 Like

Ah, as simple as that. Many thanks Paul!

1 Like

One thing, I notice that despite the return false; the page skips to the top when a card is clicked on.

That’s because return false doesn’t prevent that from occurring.

When you want to prevent the default action from occurring, calling preventDefault on the event is what’s used for that instead.

The pen at https://codepen.io/pmw57/pen/Ozazje has been updated to do just that.

1 Like

Ah, that’s only with inline JS then?

Thanks for the revised Pen.

Sorry, wrong. Returning false is not only for inline JS.
Events and default actions can be a complex issue, so it’s been well covered at https://www.quirksmode.org/js/events_early.html#link4

1 Like

Hi there gandalf458,

check out the attachment to see greatly simplified code…

gandalf458A.zip (6.7 KB)

coothead

1 Like

My brain hurts after reading that!

Thanks coothead. I suspected I could simplify it!

This attachment does away with the image preload and the CSS in the script. :winky:

gandalf458A-v1.zip (7.5 KB)

coothead

1 Like

I have just discovered that my two versions don’t seem to work on Apples (Macs and iPhones).

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.