Jonny Forney
Jonny Forney

Reputation: 2088

Call js function defined in a babel script from HTML

I am including my js file into my main html file like so

<script type="text/babel" src="js/scripts.js"></script>

Then I call one of my functions like so

<div class="allButton" id="completeAll" onclick="showAll('completeColumn');">Show All (...)</div>

the function looks like this

function showAll(column) {
  $('div[id^='+column+']').removeClass('hide');
};

When I click the button(div) I get this error Uncaught ReferenceError: showAll is not defined

I am using the text/babel as my script type because the file contains React JS stuff. I have no idea why I simply cannot call my function. I am extremely new to ReactJS and Babel. (note: I am not using npm/gulp due to limitations)

Any help and/or advice would be appreciated

Upvotes: 7

Views: 2571

Answers (2)

Miroslav Savovski
Miroslav Savovski

Reputation: 2500

If you just define your function as follows you will be able to call it within the HTML.

window.showAll = function showAll(column) {
    // your code here...
};

Upvotes: 3

Quirk
Quirk

Reputation: 1337

You have not exported your showAll function. When you transpile a JS/JSX file with Babel and bundle it to a scripts.js file (using Browserify or similar utilities), you must make sure to export your module (which tells your bundler to package it into your bundled file).

Your code should look like this:

var showAll = function(column) {
  $('div[id^='+column+']').removeClass('hide');
};

module.exports = showAll;

This tells your bundler that your showAll method needs to be exported and available to other referenced namespaces.

Upvotes: 1

Related Questions