Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPython: Adding Javascript scripts to IPython notebook

Tags:

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.

like image 911
Tarun Gaba Avatar asked May 31 '13 08:05

Tarun Gaba


People also ask

Can you use Javascript in Jupyter Notebook?

Jupyter Notebooks are documents that contain a mix of live code (Python, R, Julia, JavaScript, and more), visualizations, and narrative text (Markdown).

How do I load files into IPython?

A text file can be loaded in a notebook cell with the magic command %load . the content of filename.py will be loaded in the next cell. You can edit and execute it as usual. To save the cell content back into a file add the cell-magic %%writefile filename.py at the beginning of the cell and run it.

How do I add text to IPython notebook?

Change the cell type to Markdown in the menu bar, from Code to Markdown . Currently in Notebook 4. x , the keyboard shortcut for such an action is: Esc (for command mode), then m (for markdown). is there anyway to edit the text like make italic or bolt or change font?


2 Answers

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.

like image 145
Alex Avatar answered Oct 13 '22 00:10

Alex


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.

like image 33
Anton Tarasenko Avatar answered Oct 12 '22 23:10

Anton Tarasenko