# onClick function in JS file?

**URL:** https://discourse.roots.io/t/onclick-function-in-js-file/18853
**Category:** sage
**Created:** 2020-08-07T18:55:49Z
**Posts:** 3

## Post 1 by @tomphilpotts — 2020-08-07T18:55:49Z

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:

> [@Sage 9 - calling / use javascript custom functions / classes in template](https://discourse.roots.io/t/sage-9-calling-use-javascript-custom-functions-classes-in-template/10208/3):
>
> Any specific reason you chose this solution? Would it not be better with car/mileage container divs with data attributes that you can iterate over in the js?

[https://discourse.roots.io/t/how-do-you-add-a-simple-javascript-function-in-sage-9/11647/23](https://discourse.roots.io/t/how-do-you-add-a-simple-javascript-function-in-sage-9/11647/23)

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.

---

## Post 2 by @alwaysblank — 2020-08-07T19:11:03Z

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
  });
}
```

---

## Post 3 by @tomphilpotts — 2020-08-07T20:18:20Z

That is a really nice solution. Thank you.

Good to learn something new.

---

## Post 4 by @system — 2020-09-18T18:55:51Z

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