Reputation: 7275
I've got a means of simultaneously opening several source documents in separate tabs using IPython.display.Javascript
to help streamline error-analysis workflow.
# This opens all links in new tabs upon cell execution
def open_all(links):
# Set up onclick function
javascript = "\n".join(['window.open("{}");'.format(link) for link in links])
return javascript
js = open_all_dockets(links)
display(Javascript(js))
What I would really like to do is be able to tie the opening of these links in new tabs to a button. This would allow the notebook user to execute all the cells and still control which set of source documents to open with a click.
The problem is this only works when once the notebook is rendered to HTML.
# The button opens links in new tabs *only* once the notebook is rendered to HTML
def open_all_button(links):
# Set up onclick function
onclick = "function open() {\n"
onclick += "\n".join([" "*4 + 'window.open("{}");'.format(link) for link in links])
onclick += "}\n"
# Create button
button = "element.append('<button onclick={}>one click open source docs</button>')".format('"open()"')
# Assemble JS
javascript = onclick + button
return javascript
display(Javascript(open_all_button(links)))
How can I get this to work in a running notebook?
Thanks.
Upvotes: 2
Views: 1854
Reputation: 15941
I've had a mess around and this seems to work for both a live notebook and when output as html. I'm guessing that having the open()
function defined separately was messing things up, so we just define it within the onclick
property of the button itself.
# The button opens links in new tabs *only* once the notebook is rendered to HTML
import IPython.display as display
def open_all_button(links):
# Set up onclick function
onclick = "".join(['window.open("{}");'.format(link) for link in links])
# Create button
javascript = "element.append('<button onclick=" + onclick +">one click open source docs</button>')"
return javascript
display.Javascript(open_all_button(["https://www.google.com","https://www.google.co.uk"]))
Upvotes: 2