Removing inline JS


#1

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?


#2

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.


#3

Ah, as simple as that. Many thanks Paul!


#4

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


#5

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.


#6

Ah, that's only with inline JS then?

Thanks for the revised Pen.


#7

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


#8

Hi there gandalf458,

check out the attachment to see greatly simplified code...

gandalf458A.zip (6.7 KB)

coothead


#9

My brain hurts after reading that!

Thanks coothead. I suspected I could simplify it!


#10

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

gandalf458A-v1.zip (7.5 KB)

coothead


JavaScript not working in Safari 9
#11

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


closed #12

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