I am trying ES6 module in google chrome. I would like to launch an alert() (in an imported function) when i click on the button.
js/notification.js is well loaded but when I click on the button I get an error:
Uncaught ReferenceError: createNotification is not defined
at HTMLButtonElement.onclick ((index):24) <- line of the button in index.html
index.html
<head>
<script type="module" src="js/main.js"></script>
</head>
<body>
<section id="container">
<button type="error" onclick="createNotification()">Create</button>
</section>
</body>
js/main.js
import {createNotification} from './notification.js';
js/notification.js
export function createNotification(type){
alert();
}
Functions used in onxyz-attribute-style handlers must be globals (it's one of the many reasons not to use them). Your function isn't a global, it's local to the module in which you're importing it. (Remember: Your main script is a module too; if it weren't, you couldn't use import in it.)
You could make it a global by assigning to a window property:
window.createNotification = createNotification;
but it would be much better to use modern event handling:
document.querySelector("#container button").addEventListener("click", createNotification);
Live example on plnkr, obviously will only work on cutting-edge browsers with module support.
Side note: As Andreas points out, type="error" isn't valid for button elements. Valid types are button, submit, or reset, with submit being the default. (I've changed it to button in the plnkr.)
Related
I have two html files(index.html and project.html), index.html contain or needs two javascript files(main.js and index.js).
The main.js contains the functions that both html files needs. And the index.js has the functons that only index.html needs.
So am saying index.html-->(main.js,index.js) and project.html-->(main.js).
The issue is that when I open the project.html the DOM elements that I called in index.js is throwing errors saying that the element is null.
The thing is that the DOM element that is causing the error is only created in index.html and not project.html but project is not supposed to call or know that function.
index.html
<script src="asset/javaScript/javaScript_for_index/main.js" defer type="module"></script>
<script src="asset/javaScript/javaScript_for_index/index.js" defer type="module"></script>
project.html
<script src="asset/javaScript/javaScript_for_index/main.js" defer type="module"></script>
This is where i get the error in the inspector. Note that the error comes from the project.html and it is caused by the index.js
I know that this is a bit confusing but this is the best i can explain it.
Thanks in advance!
Two things:
Note that all your <script> elements should appear in your markup before the closing </body> element.
On each page, only reference the <script>(s) that you need for that page
Example:
index.html
<script src="main.js"></script>
<script src="index.js"></script>
</body>
</html>
project.html
<script src="main.js"></script>
</body>
</html>
Example:
index.html needs main.js and index.js
project.html needs A CERTAIN function in main.js ONLY
so main.js
function functionsThatIndexNeeds() {
alert('Im in index.html!!!');
}
function functionsThatProjectNeeds() {
alert('IM IN PROJECTS~~~');
}
index.html
<script>functionsThatIndexNeeds()</script>
projects.html
<script>functionsThatProjectNeeds</script>
The point is to call ONLY the functions that each HTML files need.
Tell me if this works on you!:)
Before we do anything start with clearing your cache. (Important)
If you are sure that you have done everything right, just like #Rounin answer suggest,
Then run your code again, inspect to make sure your error is coming from index.js and if it is, then you are somehow injecting index.js into the page without knowing , (maybe somewhere at the middle of your body or something else), you might have to do a more thorough debugging than just asking. And most probably you have not told us everything because you might not be aware of it.
Try searching for any occurrence of index.js on your project.html script. (Ctrl+F)
Now if all else fails and you have to move on fast, then u can try this hack on your index.html and index.js script.
Index.html
<script> var page = "index" </script>
Put this on line 1, before anything else, because I don't know what line might be caising your problem
Then on index.js wrap your codes with an if statement (i.e put if statements to check if the page = "index" to prevent unwanted codes from running on other pages
E.g:
If (typeof page !== undefined && page == "index") {
// allow code to execute
}
This is a dirty hack, but it might kept you going until you get a more experience engineer to debug your codes...
Obviously, you must have something in main.js that is referencing DOM parts that are in index.html. Stop referencing those, and you'll be okay. Note, that if I have a DIV in index.html with ID foo which project.html does not have, then you can use document.querySelectorAll() function to check if that element exists (can look at length, returned from that, as well as other options like undefined), and then react if it doesn't exist. That can help you delineate items from index.html versus project.html.
My index like this :
...
<html >
<head>
...
<script src="/scripts/myapp.min.js"></script>
<script src="/scripts/myapp-themming.min.js"></script>
</head>
<body class="header-static">
<div class="page-container">
<!-- this is call header, navigaton, content, footer -->
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="/Content/assets/script/jquery-ui.min.js"></script>
...
<script type="text/javascript">
...
</script>
<script>
$(document).ready(function () {
...
});
</script>
</body>
</html>
If I test pages speed using gtmetrix. And gtmetrix recommendation for Defer parsing of JavaScript. So I try to add async like this :
<script src="/scripts/myapp.min.js" async></script>
<script src="/scripts/myapp-themming.min.js" async></script>
it showing following error,
Uncaught ReferenceError: $ is not defined
If I using defer, it make 3 error like this : Uncaught ReferenceError: $ is not defined, Uncaught TypeError: $(...).material_select is not a function, and Uncaught TypeError: $(...).select2 is not a function
How can I solve this error?
First move the two scripts in the <body> into the <head> section at the top (above the 3 dots you have added). This is what #Nijin Koderi meant.
The important thing is making sure that jQuery is ABOVE everything else so it is loaded first.
Secondly - you can't just use async as mentioned in the other answer I gave as you will end up with a race condition.
The reason you get less errors with async is purely down to load speed of resources, you will find that with enough loads you will get different errors depending on which scripts download the fastest.
It is much easier while you are learning this to use defer (in fact I nearly always use defer unless you are loading megabytes of JS or your site needs JS within milliseconds to work)
To quote the answer I gave
The easiest way [to defer parsing of JavaScript] is to add defer
attribute to each JavaScript request.
For better performance (difficult) I would recommend using async
instead as this will start downloading sooner and activate each Script
as soon as it is available.
However this often causes issues with 'race conditions' where scripts
may load out of order (i.e. if you are using jQuery and another script
loads before it that needs jQuery you will get an error).
Try defer first and if performance is good use that.
You have two errors as mentioned above, Uncaught ReferenceError: $ is not defined, Uncaught TypeError: $(...).material_select is not a function, and Uncaught TypeError: $(...).select2 is not a function
the first problem can be resolved by adding the following js file on the top before any other js as shown below
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
...
<script src="/scripts/myapp.min.js"></script>
<script src="/scripts/myapp-themming.min.js"></script>
Next Error is for select2. For resolving this issue,add the following stylesheet and js file after jquery.min.js
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js">
I'm using the Brackets IDE and I tried basic JS. Using the object document sends me to an error saying
"ERROR: 'document' is not defined. [no-undef]",
I can't find out why is this error happening since it works perfectly in dreamweaver, does anyone know why is this happening in Brackets? Thank you.
HTML:
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>Parrafos</title>
</head>
<body>
<p>a</p>
<p>aa</p>
<p id="special">especial</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="javascript" src="parrafos.js"></script>
</body>
</html>
JS:
function parrafo(texto, id) {
document.getElementById(id).textContent = texto;
}
parrafo("Hola qué tal", "especial");
document is not part of JavaScript, it is part of the browser DOM.
Whatever linter (e.g. JSHint, JSLint, ESLint) you have configured Brackets to use to test you code with hasn't been configured to assume the presense of global variables that exist when you run the code through a script element in an HTML document.
Consult the documentation for whichever linter you are using to find out how to do that (likely this will either be a configuration file in the root of your project directory or a specially formatted comment at the top of your JS file).
"ERROR: 'document' is not defined. [no-undef]" Means that every variables should be declared, in top of your code state: var document; or disable lint from checking [no-undef]
UPDATE
After the comments, if you want to pick the first option you can write:
var document = window.document;
to suppress the message and be clear
Before you ask, yes I've been using Browserify multiple times, but for some reason it just won't work this time.
The problem:
When I load up the website, bundle.js will only be executed once, then be ignored for the rest of the time. - Require is not the problem, since I tried to Console.log some require code, which worked, but afterwards, anything done by the user won't be executed.
As you can see in my code, I'm trying to execute registerHref() onclick of my button, which works when I'm not using bundle.js, but as soon as I'm doing this with my bundle, it's like it's being completely ignored. I will get an error which says: Uncaught ReferenceError: registerHref is not defined at HTMLButtonElement.onclick - But when I try to console.log the function on window.onload - it works as it should.
My HTML:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="bundle.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="header" style="border-style: solid; text-align: center;">
<button id="register" onclick="registerHref()">Register</button>
</div>
</body>
</html>
My Javascript:
function registerHref() {
window.location.href = "./register.html"
}
What I did:
I made my bundle using: browserify main.js > bundle.js <- Usually works fine
The problem is that after the code gets compiled the function isn't attached to the window object but instead is executed within a different scope.
You have basically two options here:
Attach the registerHref function to the window object (not recommended):
function registerHref() {
window.location.href = "./register.html"
}
window.registerHref = registerHref;
Create an event listener in your JS code and remove the onclick attribute from your HTML (recommended):
function registerHref() {
window.location.href = "./register.html"
}
document.getElementById('register').addEventListener('click', registerHref);
I'm very new to JavaScript (just started a few hours ago and trying to get a script working). I went through a few tutorials on W3 and the 'hello world' code works when I paste it directly into my HTML but I'm having a problem with a script (I've had problems with other scripts as well but I am not sure what I'm doing wrong).
I have this code that I want to test in my HTML, I copied the HTML in and it looks the same then I made a file in my static folder called edit.js and copied the JavaScript into it (exactly as shown). It didn't work no errors on the page but when I click it nothing happens. I tried to paste a W3 'hello world' code in and that worked but this script does not.
I tried to inspect the code in Chrome and that's where I see the above error (under the resources tab). I can open the js file using Chrome which makes me think the js file is accessible and pointing correctly but I'm not sure how to get it working. I'm using Jinja2 as my template engine to render the HTML and in my header I have:
<script language="JavaScript" type="text/javascript" src="static/edit.js"></script>
and in my main template (the one that gets rendered on all pages) I have:
<script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
edit.js:
(even putting it within the script tag directly on the page I want to use it on doesn't work)
$('#editvalue').click(function(e){$('#storedvalue').hide();$('#altervalue').show();});
$('#savevalue').click(function(e){
var showNew = $('#changevalue').val();
$('#altervalue').hide();
$('#storedvalue').show();
$('#storedvalue span').text(showNew);
});
HTML:
(it's embedded in a larger page)
<head>
<script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript" src="static/edit.js"></script>
</head>
... my html code..
<div id="wrapper">
<div id="container">
<div id="storedvalue"><span>Hello</span> [edit]</div>
<div id="altervalue" style="display:none;"><input type="text" name="changevalue" id="changevalue" value="Hello"> [save]</div>
</div>
</div>
I have never been able to successfully run a JavaScript that wasn't on W3 yet. I get the same problem with other scripts even though I see people online saying they work fine for them. Do I need to do anything extra to make this work?
My two questions are:
What am I doing wrong?
Because Javascript seems to just not work when there's a problem, is there a way to get errors or information on what's actually wrong?
I read Uncaught ReferenceError: $ is not defined? and have been trying to figure this out for the last hour and can't see my problem.
First you need to place the jQuery script tag first.
Second, you need to do one of the following things:
Put your code within this function:
$(document).ready(function(){/*CODE HERE*/});
Or like this:
$(function(){
/*CODE HERE*/
});
The DOM needs to be ready before you can use it. Placing your code within anonymous functions that are executed on the ready event of the DOM is how you can do this.
Edit:
$(function(){
$('#editvalue').click(function(e){$('#storedvalue').hide();$('#altervalue').show();});
$('#savevalue').click(function(e){
var showNew = $('#changevalue').val();
$('#altervalue').hide();
$('#storedvalue').show();
$('#storedvalue span').text(showNew);
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
Script tag for jQuery should come before your custom javascript.
Follow by edit.js
<script type="text/javascript" src="static/edit.js"></script>
Try removing the language attribute..sometimes work for me. It's obsolete now .. i think
You need to include jquery before you can use it.