onClick function in JS file?

Hi

How do you call a function in a js file with onClick? I have been trying to get this to work and have read through:


but none seem to have a clear route on how to solve their issues.

Problem:

// blade
<ul>
    <li onclick="do_something(this)" data-slug="alabaham" data-name="Alabaham">Alabaham</li>
    <li onclick="do_something(this)" data-slug="alaska" data-name="Alaska">Alaska</li>
    <li onclick="do_something(this)" data-slug="arizona" data-name="Arizona">arizona</li>
</ul>

// state.js
function do_something(this)
{
console.log'this)
}

Uncaught ReferenceError: do_something is not defined
at HTMLButtonElement.onclick

I am trying to keep the JS out of the blade files to keep things tidy.

The function do_something() doesn’t exist in the scope where it’s called in the browser. If you really need access to, the easiest (but not the ideal) solution is to attached it to the window object, which will be available when it executes in the browser, i.e.

window.do_something = function() {
  // do something
}

Usually, though, the better solution is to write JS that watches for events instead of using onclick and its bretheren:

const clickers = document.querySelectorAll(`[data-slug]`);
if (clickers && clickers.length > 0) {
  Array.from(clickers).map(clicker => clicker.addEventListener(`click`, (e) => {
    // do something
  });
}
3 Likes

That is a really nice solution. Thank you.

Good to learn something new.

This topic was automatically closed after 42 days. New replies are no longer allowed.