onClick to call function from another JS file with react - javascript

I have the following html code in my render react component:
<button id="execute-request-button">Authorize</button>
And I am trying to call this function from my external JS file
$("#execute-request-button").click(function() {
console.log("CLICK");
handleAuthClick(event);
});
I am calling the external JS file in my HTML as well. It doesn't print to the console when I click my authorize button. Also I console logged at the very first of the external JS file to see if it's loaded and its not. I know the file path is right since I am not getting any errors.
Any thoughts?
EDIT
I moved my script tag to the top of my html file .
<script src="../src/YoutubeAPI/upload.js"></script> and I get the following error Refused to execute script from 'http://localhost:3000/src/YoutubeAPI/upload.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="../src/YoutubeAPI/upload.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<title>STEMuli</title>
</head>
<body>
<noscript>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T"
crossorigin="anonymous"></script>
</noscript>
<div id="root"></div>
</body>
</html>

I think you add event click before your code render html.
You can try:
<button id="execute-request-button" onclick="yourEvent()">Authorize</button>
and define yourEvent is method of your component.

Add your event listener when the document is ready:
$(document).ready(()=> {
$("#execute-request-button").click(function() {
alert()
});
})
Example: https://jsfiddle.net/n5u2wwjg/90476/

I see nothing wrong with the code. Remember to place the reference to jQuery before your own Javascript file. If you place it after, the methods in your own Javascript file will be undefined as it is calling jQuery.
$("#execute-request-button").click(function() {
console.log("CLICK");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="execute-request-button">Authorize</button>

Related

How to use HTML file variables in external JS file

I have an html file where I import a JS module from chessboard.js
<html lang="en">
<head>
<link rel="stylesheet" href="./chessboardFiles/css/chessboard-1.0.0.min.css" />
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script id="import" src="./chessboardFiles/js/chessboard-1.0.0.js"></script>
<title></title>
</head>
<body>
<div id="board1" style="width: 400px"></div>
<script>
var board2 = Chessboard("board1", "start");
</script>
</body>
</html>
The only problem is that I want to write what's in the body's <script> tag in a separate JS file then add it to this html document via <script src='...'> however the <script id="import" ...> file that is imported is not exactly a module so I cant just do import * as C from chessboard-1.0.0.js in a new JS file because I get a
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. error in the console.
So is there any way to get the variables available in the HTML document (i.e Chessboard()) available in an external JS file? How could I do this?
You could write to global window variables, or have everything in the window scope. Ex: window.board = Chessboard(...), and you can access that from different files if the script is run later than the definition.

ReactJS: Uncaught ReferenceError: $ is not defined [duplicate]

How come this code throws an
Uncaught ReferenceError: $ is not defined
when it was OK before?
$(document).ready(function() {
$('#tabs > ul').tabs({ fx: { opacity: 'toggle' } });
$('#featuredvid > ul').tabs();
});
Results in tabs don't close anymore.
jQuery is referenced in the header:
<script language="JavaScript" type="text/javascript" src="<?php echo get_option('siteurl') ?>/js/sprinkle.js"></script>
<script language="JavaScript" type="text/javascript" src="<?php echo get_option('siteurl') ?>/js/jquery-1.2.6.min.js"></script>
<script language="JavaScript" type="text/javascript" src="<?php echo get_option('siteurl') ?>/js/jquery-ui-personalized-1.5.2.packed.js"></script>
You should put the references to the jquery scripts first.
<script language="JavaScript" type="text/javascript" src="/js/jquery-1.2.6.min.js"></script>
<script language="JavaScript" type="text/javascript" src="/js/jquery-ui-personalized-1.5.2.packed.js"></script>
<script language="JavaScript" type="text/javascript" src="/js/sprinkle.js"></script>
You are calling the ready function before the jQuery JavaScript is included. Reference jQuery first.
This is what solved it for me. Originally I went to Google and copied and pasted their suggested snippet for jQuery on their CDN page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
The snippet does not include the HTTP: or HTTPS: in the src attribute but my browser, FireFox, needed it so I changed it to:
edit: this worked for me with Google Chrome as well
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Then it worked.
If your custom script is loaded before the jQuery plugin is loaded to the browser then this type of problem may occur. So, always keep your own JavaScript or jQuery code after calling the jQuery plugin so the solution for this is :
First add the link to the jQuery file hosted at GoogleApis or a local jQuery file that you will download from http://jquery.com/download/ and host on your server:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
or any plugin for jQuery. Then put your custom script file link or code:
<script src="js/custom.js" type="text/javascript"></script>
In my case I was putting my .js file before the jQuery script link, putting the .js file after jQuery script link solved my issue.
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="exponential.js"></script>
Add the library before you start the script.You can add any of these following CDN to start it.
Google:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Microsoft
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
Jquery
If you want any other Jquery cdn version check this link.
After this:
<script type="text/javascript">
$(function(){
//your stuff
});
or
$(document).ready(function(){
//your stuff
});
</script>
Wordpress:
<script type="text/javascript">
var $ = jQuery;
jQuery(document).ready(function($){
//your stuff
});
</script>
Okay, my problem was different - it was Document Security model in Chrome.
Looking at the answers here, it was obvious that I was somehow not loading my jquery files before calling the $(document).ready() etc. functions. However, they were all in the correct positions.
In my case, this was because I was accessing the content over a secure HTTPS connection, whereas the page was trying to download the CDN hosted data from google, etc. The solution was to store them locally and then include then directly rather than from the CDN each time.
Edit: The other way of doing this is to link to all the CDN-hosted stuff as https:// rather than http:// - then the model doesn't complain.
You are calling the ready() function before the jQuery JavaScript is included. Reference jQuery first.
If you're in ASP.NET MVC, you can specify when your JS code should be rendered, by doing this:
1, In your page.cshtml wrap your <script> tag into a section, and give it a name, the common name to use is 'scripts':
#section scripts {
<script>
// JS code...
</script>
}
2, In your _Layout.cshtml page add #RenderSection("Scripts", required: false), make sure to put it after you reference the Jquery source, this will make your JS code render later than the Jquery.
Add jQuery library before your script which uses $ or jQuery so that $ can be identified in scripts.
remove tag script on head and put end bady
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
then first write script in file js add
/*global $ */
$(document).ready(function(){ });
If it's in wordpress, might be needed to change
$(document).ready(function() {
to
jQuery(document).ready(function($){
or add
var $ = jQuery;
before
$(document).ready(function() {
I had the exact same problem and none of these solutions above helped.
however, I just linked the .css files after the .js files and the problem miraculously disappeared. Hope this helps.
In my case I had this referenceError as the order of script calls was wrong. Solved that by changing the order:
<script src="js/index.js"></script>
<script src="js/jquery-1.10.2.js"></script>
to
<script src="js/jquery-1.10.2.js"></script>
<script src="js/index.js"></script>
I wanted to try to make my script asynchronous. Then I forgot about it and when I went live the [custom].js file only loaded 50% of the time before the jQuery.js.
So I changed
<script async src="js/script.js"></script>
to
<script src="js/script.js"></script>
I had the same problem , and I solved by putting jQuery at the top of all javascript codes I have in my code.
Something like this:
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="js/app.js" type="text/javascript"></script>
<script src="js/form.js" type="text/javascript"></script>
<script src="js/create.js" type="text/javascript"></script>
<script src="js/tween.js" type="text/javascript"></script>
Hope can help some one in future.
put latest jquery cdn on top of your main html page
Like If your main html page is index.html
place jquery cdn on top of this page like this
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("h2").hide();
});
});
</script>
</head>
<body>
<h2>This will hide me</h2>
<button>Click me</button>
</body>
</html>
Include the jQuery CDN (or jQuery ref) in the index file first. before including your JS file to ensure we are accessing the jQuery.
following lines worked for me
Can get a clear idea about this by referring to the following link
reference site:
https://www.tutorialrepublic.com/faq/how-to-fix-dollar-is-not-defined-error-in-jquery.php
Answer: Execute Code after jQuery Library has Loaded
The most common reason behind the error "Uncaught ReferenceError: $ is not defined" is executing the jQuery code before the jQuery library file has loaded. Therefore make sure that you're executing the jQuery code only after jQuery library file has finished loading.
In my case it was a typo, I forgot a backslash and was referencing the source incorrectly.
Before src="/scripts/jquery.js"
After src="scripts/jquery.js"
If you are doing this in .Net and have the script file referenced properly and you jQuery looks fine, make sure that your users have access to the script file. The project I was working on (a coworker) had their web.config denying access to anonymous users. The page I was working on was accessible to anonymous users therefore they didn't have access to the script file. Dropped the following into the web.config and all was right in the world:
<location path="Scripts">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
The source file jquery-1.2.6.min.js is not called the jQuery command $() is executed earlier than <..src='jquery-1.2.6.min.js'>.
Please run <.. src="/js/jquery-1.2.6.min.js.."> at first and make sure the src path is right, then execute jquery command
$(document).ready(function()
This happened to me before.
The reason was that I'm connecting android to a webview with a JS. And I sent a parameter without quotes.
js.sayHello(hello);
and when I changed it to
js.sayHello('hello');
it worked.
The error will occur in the following two scenarios as well.
#section scripts element is missing from the HTML file
Error in accessing DOM elements. For example accessing of DOM element is mentioned as $("js-toggle") instead of $(".js-toggle"). Actually the period is missing
So 3 things to be followed - check required scripts are added, check if it is added in the required order and third syntax errors in your Java Script.
I had similar issue. My test server was working fine with "http". However it failed in production which had SSL.
Thus in production, I added "HTPPS" instead of "HTTP" and in test, i kept as it is "HTTP".
Test:
wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', array(), null, false );
wp_register_script( 'custom-script', plugins_url( '/js/custom.js', __FILE__ ), array( 'jquery' ) );
Production:
wp_register_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', array(), null, false );
wp_register_script( 'custom-script', plugins_url( '/js/custom.js', __FILE__ ), array( 'jquery' ) );
Hope this will help someone who is working on wordpress.
Your JavaScript file is missing so this error occurred. Just add the JavaScript file inside the <head> tag. See the example:
<script src="js/sample.js" type="text/javascript"></script>
<link href="css/sample.css" rel="stylesheet" type="text/css" />
or add the following code in tag :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
In my case i forgot to include this :
<script src ="jquery-2.1.1.js"></script>
Earlier I was including just jquery-mobile which was causing this error.
I modified the script tag to point to the right content and changed the script order to be the right one in the editor. But totally forgot to save the change.
Doh! I had mixed quotes in my tags that caused the jquery reference to break. Doing an inspect in Chrome allowed me to see that the file wasn't properly linked.
You have not referenced a jQuery library.
You'll need to include a line similar to this in your HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
I had a similar issue and it was because I was missing a closing > on a style sheet link.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="local_xxx.js"></script>
I have similar issue, and you know what, it's because of network is disconnected when I test in android device webview and I don't realize it, and the local js no problem to load because it doesn't need network. It seems ridiculous but it waste my ~1 hour to figure out it.
if you are laraveling that error comes on in blade files when you forgot to surround the code with :
#section('section name')
.......
#endsection

JQuery library not available in another script when loaded first

I have a single HTML page with various JS imports.
I'm importing JQuery, then a custom script of my own, which I'd like to use the JQuery library in, though I get a '$ is not defined' exception.
I thought as I'm loading up JQuery first, I should be able to reference it in my external script?
Is this something RequireJS would solve?
baseTemplate.html
<body>
<template id="navbar"></template>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script src="navbarTemplate.js"></script>
</body>
navbarTemplate.js
function isTemplateElementSupported() {
return 'content' in document.createElement('template');
}
if (isTemplateElementSupported()) {
$('#navbar').append("<table><tr><td><b>some test</b></td></tr></table>");
} else {
alert('Please update browser!');
}
Try to use "defer" option for correct load sequence of your javascripts.
<body>
<template id="navbar"></template>
<script defer src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script defer src="navbarTemplate.js"></script>
</body>

External file script is not loading

Iam using load() for loading external html file.
$("#header_section").load("header.html");
$("#sidemenu_section").load("side_menu.html");
Here, HTML file is loaded and css also loaded but script file is not loading in the page
<script src="js/utility.js"></script>
I tried to declare the above script file inside the head and inside the body. Both are not working.
Check your relative path to the utility.js file and make sure to load juery.js library before load utility.js file.
and finally try this,
<script type="text/javascript" src="${pageContext.request.contextPath}/js/utility.js"></script>
to load the utility.js file.
I think you forget to add jquery.min.js file. use below code.
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/utility.js"></script>
</head>
jQuery may only execute your code with the type attribute set to "text/javascript", per this bug filed a long time ago:
http://bugs.jquery.com/ticket/3733
Try this ...
<script type="text/javascript" src="http://your.cdn.com/first.js"></script>
<script type="text/javascript">
loadScript("http://your.cdn.com/second.js", function(){
//initialization code
});
</script>
The jQuery code that adds HTML to the DOM always strips out <script> tags. It runs them and then throws them away.
An exception to that behavior is when you use "$.load()" with the hack that allows you to load a fragment of a page:
$.load("http://something.com/whatever #stuff_I_want", function() { ... });
In that case, the scripts are stripped and not evaluated/run.

Calling a function from one JavaScript file which requires another

I am trying to call a function written in one JavaScript file from another JavaScript file. I have the following code, but it doesn't work:
My HTML file
<script type="text/javascript" src="js1.js"></script>
<script type="text/javascript" src="js2.js"></script>
<script language="javascript">
js1();
</script>
js1.js
function js1()
{
alert("Hello from js1");
js2();
}
js2.js
function js2()
{
alert("Hello from js2");
}
What can I do?
Try changing the order
<script type="text/javascript" src="js2.js"></script>
<script type="text/javascript" src="js1.js"></script>
<script language="javascript">
js1();
</script>
Because you call js2(); inside js1.js, so the script js2.js should be executed before.
In your case, i think it should still work without changing orders like this because you call js2(); inside a function. When this script is executed:
function js1()
{
alert("Hello from js1");
js2();
}
Even the js2.js is not executed yet, but you do not actually call js2(); at this time.
Just try it to see if it works.
I'm going to assume that's your entire HTML page.
In order to have those scripts run, you need to have those JavaScript files in the same folder as your webpage, and to actually have a proper HTML page!
In your HTML page, you need to include the references to your js1 and js2 files in either the head or body, and include the script you've written in the HTML page itself in the body so that it'll execute when it's loaded:
<!DOCTYPE html>
<!-- ^ Declaring this DOCTYPE means this is a HTML5 page. -->
<html>
<head>
<!-- This will load your scripts into the document. -->
<script src="js1.js"></script>
<script src="js2.js"></script>
<!--
In a HTML5 page, you don't need to include the
'type="text/javascript"' attribute on script tags.
They're treated as having that by default, unless you say otherwise.
-->
</head>
<body>
<!--
You could also include your scripts here, but I'll
just leave these commented out since they're already included.
<script src="js1.js"></script>
<script src="js2.js"></script>
-->
<script>
js1();
</script>
<!--
You don't need 'language="javascript"' on a script tag.
Use the type attribute, or nothing in a HTML5 page.
-->
</body>
</html>

Categories

Resources