I made a little script to just highlight for myself some words automatically because I am useing Html format to write personal notes.
It works if I let everything in the same file but it's impossible to understand how to import and export works; I even downloaded a sample package from here and it doesn't work either.
I know there is big packaging existing to do the same thing but I just want to push a simple "js" file in the same folder and let it do the work, I just need to import/export to don't have to rewrite each time I modify the common ".js" (for coloring).
Perhaps I don't use the good keyword, but I don't find any correct information.
I will let a basic sample of my code (for the while they are in the same folder)
//csharp.js
import "./ColorText.js"
function foo(){
const blueWords = ["Task", "TaskScheduler", "void"];
var xx = document.getElementsByClassName("csharp");
for (i=0;i<xx.length;i++){
var str=xx[i].innerHTML;
ColorTextInBlue(xx[i], "Task");
}
}
I tried this part even with "//target..." to disable it.
export{ColorTextInBlue};
function ColorTextInBlue(target, str)
{
target.innerHTML=target.innerHTML.replace(new RegExp(str, 'g'),
"<font color=\"#0000FF\">"+str+"</font>");
}
HTML part
<!-- Scripts -->
<script type="module" src="./ColorText.js" ></script>
<script src="./CSharp.js" ></script>
I read there is something about a javascript revision but it's not clear at all.
If possible modify directly the code to see how it must be done.
Code edited to remove the dot, the second loop and to simplify the code.
Related
This is my first question on StackOverflow, so I hope I'm including all the necessary. If not, please let me know and I will amend accordingly.
I'm trying to get Typed.JS to work on this Roman numeral converter page. I would like the converted number to render with the "typing" effect, but I can't get it to work.
The number does render and I don't see any errors in the console, but the typing effect is missing.
In my script.js file, I have imported Typed and also included it in the HTML (I couldn't understand if only one of them was necessary. The docs don't say much)
import Typed from typed.js;
<script src="https://cdn.jsdelivr.net/npm/typed.js#2.0.12"></script>
and the function that includes it is as per below. It takes the user input as argument/parameter and displays it on the page.
This is the repo link: https://github.com/Antonio-Riccelli/js-roman-numeral-converter
function outputRomanNumeral(roman) {
let options = {
strings: [`${roman}`],
typeSpeed:90,
};
let par = document.getElementById("output");
par.classList.remove("bg-danger", "text-white", "error-message")
let typed = new Typed('#spanOutput', options);
par.classList.add("border-bottom", "border-dark", "border-2");
}
Appreciate any feedback you can provide. Thanks.
Firstly, the way you are importing typed.js is incorrect. You need quotes around it, although that wouldn't actually work either. You are trying to import it when you have the typed.js NPM package installed, but that only works if you have a module bundler such as Webpack.
In your case, there are a couple of things that might work.
Import from CDN. import Typed from "https://cdn.jsdelivr.net/npm/typed.js#2.0.12";
Use the script tag, the library might use globals.
I'm doing a javascript course with FCC and use VSCode as my code editor. But to date, all my js code was contained in a single file. Obviously for any meaningful js development I need to create a collection of js files that work as a single unit.
To start exploring this I have a very simple setup of two js files, test-01.js and test-02.js, where test-01.js contains a call to a function which is defined in test-02.js. I first want to do this without any HTML or CSS files. Although that will also be a future requirement.
The first file test-01.js:
//test-01.js
let returnStr = "";
console.log("This is the calling program");
// Now call the function in test-02.js
returnStr = Display(10);
With future project complexity in mind, the second file test-02.js is in a sub-folder from the first file. .\folder-02\test-02.js:
//test-02.js
function Display(param = 0) {
console.log("This is the program called with parameter: ", param);
return "Back from Display";
};
I've unsuccessfully tried importing the function Display() from test-01.js into test-02.js.
I've unsuccessfully tried finding ways to modify files like:
package.json
jsconfig.json
setting.json
launch.json
I've unsuccessfully tried looking for sample projects on github and elsewhere.
I've unsuccessfully looked for answers in StackOverflow.
All to no avail. This should be a no brainer which should have been described in the vscode documentation but I cannot find it there. By now I have tried so many things that I've probably screwed up my development environment. I hope someone can help me out and point me in the right direction to resolve this.
Many thanks, Thomas.
JavaScript modules are the way to go when importing methods from one .js file and calling them in another .js file. There are many different ways to import and use modules in JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
Here is an example for your situation:
First, lets import the main JavaScript file into the html document:
<head>
<!-- type="module" is necessary -->
<script type='module' src="test-01.js" defer></script>
</head>
Next, lets define the 'Display' function in folder-02/test-02.js:
function Display(param = 0) {
console.log("This is the program called with parameter: ", param);
return "Back from Display";
};
export default Display //exporting it to be imported into another js file
Lastly, lets set up test-01.js to import and call the previously defined function:
import Display from './folder-02/test-02.js';
let returnStr = "";
console.log("This is the calling program");
// Now call the function in test-02.js
returnStr = Display(10);
I decided to use Google Cloud Translation API for my project. Everything seemed fine until the moment I tried to run their script. It always says that I need to "Use require([])".
Right after I add square brackets inside my require's argument, it says I have to remove braces around Translate variable, 'cause it's not a constructor (though, in Google's script it is coded SO). I do that, and I get even more errors. Like this:
I dunno how to fix that. Spent whole days trying to figure out what's wrong, but haven't done any progress ever since. Maybe, I'm lacking the translate.js file, since it indicates that on the 2nd picture. But I did everything as said in Quickstart tutorial on Google's official website, and the following command (npm install #google-cloud/translate) does download many packages, but doesn't do anything justice, meaning, it doesn't download any translate.js or something of that sort.
The source code is below:
index.html:
<html>
<head>
<script src="https://requirejs.org/docs/release/2.3.6/minified/require.js"></script>
<script src="test.js"></script>
</head>
<body><script>main()</script></body>
</html>
test.js:
async function main(
projectId = 'text-analyzer-1571113830391' // Your GCP Project Id
) {
// [START translate_quickstart]
// Imports the Google Cloud client library
const Translate = require(['#google-cloud/translate']);
// Instantiates a client
const translate = new Translate({projectId});
// The text to translate
const text = 'Hello, world!';
// The target language
const target = 'ru';
// Translates some text into Russian
const [translation] = await translate.translate(text, target);
console.log(`Text: ${text}`);
console.log(`Translation: ${translation}`);
}
// [END translate_quickstart]
Thanks to #Kolban, I've recalled that Node.js is a server-side API, and it can't do any logic in a browser. To do that, you have to use some third-party product like Webpack to transform your code or, either way, make REST calls via Ajax. Thanks again, Kolban!
The topic can be closed.
As a part of a project, I need to embedd some javascripts inside an IPython module.
This is what I want to do:
from IPython.display import display,Javascript
Javascript('echo("sdfds");',lib='/home/student/Gl.js')
My Gl.js looks like this
function echo(a){
alert(a);
}
Is there some way so that I can embed "Gl.js" and other such external scripts inside the notebook, such that I dont have to include them as 'lib' argument everytime I try to execute some Javascript code which requires to that library.
As a very short-term solution, you can make use of the IPython display() and HTML() functions to inject some JavaScript into the page.
from IPython.display import display, HTML
js = "<script>alert('Hello World!');</script>"
display(HTML(js))
Although I do not recommend this over the official custom.js method, I do sometimes find it useful to quickly test something or to dynamically generate a small JavaScript snippet.
Embedding D3 in an IPython Notebook
https://blog.thedataincubator.com/2015/08/embedding-d3-in-an-ipython-notebook/
To summarize the code.
Import the script:
%%javascript
require.config({
paths: {
d3: '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.min'
}
});
Add an element like this:
%%javascript
element.append("<div id='chart1'></div>");
Or this:
from IPython.display import Javascript
#runs arbitrary javascript, client-side
Javascript("""
window.vizObj={};
""".format(df.to_json()))
IPython Notebook: Javascript/Python Bi-directional Communication
http://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/
A more extensive post explaining how to access Python variables in JavaScript and vice versa.
I've been fighting with this problem for several days now, here's something that looks like it works; buyer beware though, this is a minimal working solution and it's neither pretty nor optimal - a nicer solution would be very welcome!
First, in .ipython/<profile>/static/custom/myScript.js, we do some require.js magic:
define(function(){
var foo = function(){
console.log('bar');
}
return {
foo : foo
}
});
Copy this pattern for as many functions as you like. Then, in .ipython/<profile>/static/custom/custom.js, drag those out into something persistent:
$([IPython.events]).on('notebook_loaded.Notebook', function(){
require(['custom/myScript'], function(custom){
window.foo = custom.foo;
} );
});
Yes, I am a horrible person for throwing stuff on the window object, namespace things as you deem appropriate. But now in the notebook, a cell like
%%javascript
foo();
should do exactly what it looks like it should, without the user having to explicitly import your JS. I would love to see a simpler solution for this (plz devs can we plz have $.getScript('/static/custom/util.js'); in custom.js to load up a bunch of global JS functions) - but this is the best I've got for now. This singing and dancing aside, HUGE ups to the IPython notebook team, this is an awesome platform!
Not out of the box by installing a package, at least for now.
The way to do it is to use custom.js and jQuery getScript to inject the js into the notebook.
I explicitly stay vague on how to do it, as it is a dev feature changing from time to time.
What you should know is that the static folder in user profile is merged with webserver static assets allowing you to access any file that are in this folder by asking for the right url.
Also this question has been asked a few hours ago on IPython weekly video "lab meeting" broadcasted live and disponible on youtube (you might have a longer answer), I've opened discussion with the author of the question here
For some reason, I have problems with IPython.display.Javascript. Here is my alternative, which can handle both importing external .js files and running custom code:
from IPython.display import display, HTML
def javascript(*st,file=None):
if len(st) == 1 and file is None:
s = st[0]
elif len(st) == 0 and file is not None:
s = open(file).read()
else:
raise ValueError('Pass either a string or file=.')
display(HTML("<script type='text/javascript'>" + s + "</script>"))
Usage is as follows:
javascript('alert("hi")')
javascript(file='Gl.js')
javascript('echo("sdfds")')
You can use IJavascript (a Javascript kernel for Jupyter notebooks).
I was interested in calling JavaScript from a Jupyter code (Python) cell to process strings, and have the processed string output in the (same) code cell output; thanks to Inject/execute JS code to IPython notebook and forbid its further execution on page reload and Why cannot python call Javascript() from within a python function? now I have this example:
from IPython.display import display, Javascript, Markdown as md, HTML
def js_convert_str_html(instring_str):
js_convert = """
<div id="_my_special_div"></div>
<script>
var myinputstring = '{0}';
function do_convert_str_html(instr) {{
return instr.toUpperCase();
}}
document.getElementById("_my_special_div").textContent = do_convert_str_html(myinputstring);
</script>
""".format(instring_str)
return HTML(js_convert)
jsobj = js_convert_str_html("hello world")
display(jsobj)
Note that the JavaScript-processed string does not get returned to Python per se; rather, the JavaScript itself creates its own div, and adds the result of the string conversion to it.
I am making use of constructors (classes) extensively and would like each constructor to be in a separate file (something like Java). Suppose I have constructors say Class1, Class2, ... Class10 and I only want to use Class1 and Class5 I need to use script tags to include Class1.js and Class2.js into the HTML page. Later if I also need to use Class3 and Class6 I again need to go to the HTML page and add script tags for them. Maintenance with this approach is too poor.
Is there something in JavaScript similar to include directive of C? If not, is there a way to emulate this behavior?
You can use jQuery.getScript:
http://api.jquery.com/jQuery.getScript
Or any of the many javascript loaders like YUI, JSLoader, etc. See comparison here:
https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ
You can use something like this:
jsimport = function(url) {
var _head = document.getElementsByTagName("head")[0];
var _script = document.createElement('script');
_script.type = 'text/javascript';
_script.src = url;
_head.appendChild(_script);
}
then use it in your code like:
jsimport("example.class.js");
Be careful to use this when the head is already in the DOM, else it won't work.
Yes: You can create script tags from JavaScript and load required classes on demand.
See here for a couple of solutions: http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html
With careful use of id attributes or a global variable that contains "already loaded" scripts, it should be possible to develop a dependency resolution framework for JavaScript like Maven or OSGi for Java.
When we are talking about JavaScript, I feel it is better to include one file that includes everything you need instead of requesting a new file every time you need something that you don't currently have access to.
Each time you send out for another file, the browser will do many things. It checks if the requested file can in fact be found by sending an HTTPRequest, and if the browser has already seen this, is it cached and unchanged?
What you are wanting to do is not in the spirit of JavaScript. Doing what you are explaining will produce addition load times, and you wouldn't be able to do anything until the file has completely loaded, which creates wait times.
It would be better to use one file for this, include at the inner end of the </body tag (which won't cause the browser to wait until the script is done to load the page), then create one simple function that will execute when the page is completely loaded.
For example:
<html>
<head></head>
<body>
<!-- HTML code here... -->
<script src="javascript.js"></script>
<script>
(function r(f) {
/in/.test(document.readyState) ? setTimeout('r(' + f + ')', 9) : f()
})(function() {
// When the page has completey loaded
alert("DOM has loaded and is ready!");
});
</script>
</body>
</html>
you can include one js file into another js file by doing something like this in the begginig of your js file:
document.write("<script type='text/javascript' src='another.js'></script>");
The best approach in your situation is using of compiler of some kind. The greatest one is Google Closure Compiler. This is part of Google Closure Libraty which has structure similar to what you described.