Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 485
Jonny Forney Avatar asked Mar 25 '16 19:03

Jonny Forney


People also ask

How do you call function in JS file from HTML?

Calling a function using external JavaScript file Once the JavaScript file is created, we need to create a simple HTML document. To include our JavaScript file in the HTML document, we have to use the script tag <script type = "text/javascript" src = "function.

How do you call a function in HTML?

Step 1: Firstly, we have to type the script tag between the starting and closing of <head> tag just after the title tag. And then, type the JavaScript function. Step 2: After then, we have to call the javaScript function in the Html code for displaying the information or data on the web page.

How do you add Babel in HTML?

Use it via UNPKG: https://unpkg.com/@babel/standalone/babel.min.js. This is a simple way to embed it on a webpage without having to do any other setup. Install via NPM: npm install --save @babel/standalone.


2 Answers

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...
};
like image 91
Miroslav Savovski Avatar answered Sep 28 '22 03:09

Miroslav Savovski


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.

like image 31
Quirk Avatar answered Sep 28 '22 05:09

Quirk