Back to jQuery
In [1]:
from IPython.display import HTML, Javascript
from ipywidgets import interact
Create a HTML element with a class and a tag
In [2]:
HTML("""<h1 class='juh' id='juhh1'>Hello World</h1>""")
Out[2]:
Change the style/color of the previously created element
In [3]:
Javascript("""
$("#juhh1").css('color', 'red')
""")
Out[3]:
In [4]:
Javascript("""
$("#juhh1").css('color', 'green')
""")
Out[4]:
def changeDOMColor(color):
Javascript("""
$("#juhh1").css("color", '{0}');
""".format(color))
interact(changeDOMColor, color=['red', 'green', 'blue'])
Why is Javascript code not being executed? :(
SOLVED :)
In order for the Javascript() function to take effect, I had to save it in a variable and return it.
In [5]:
HTML("""<h1 class='juh' id='juhh2'>jQuery and ipywidgets</h1>""")
Out[5]:
In [6]:
def changeDOMColor(color):
js = Javascript("""
$("#juhh2").css("color", '{0}');
""".format(color))
return js
interact(changeDOMColor, color=['red', 'green', 'blue'])
Using the f-string syntax in Python 3.6 makes it even easier to write templated strings.
As you can see in the code below, the f-string starts with f" and the variable in the scope is interpolated {variable}
In [7]:
HTML("""<h1 class='juh' id='juhh3'>Using Python 3.6 f-strings</h1>""")
Out[7]:
In [8]:
def changeDOMColor(color):
js = Javascript(f"""
$("#juhh3").css("color", '{color}');
""")
return js
interact(changeDOMColor, color=['red', 'green', 'blue'])