I'm taking a course on data visualization in Python and right now we're looking at some basic stuff about HTML and Javascript.
The following code makes a simple HTML box using the command %%hmtl
from a Jupyter notebook.
## Esto se ejecuta en una celda
%%html
<style>
#boton
{
width: 60px;
height: 50px;
background-color: grey;
color: white;
text-align: center;
}
</style>
<div id="boton"></div>
Now, to create events on the box, we use %%javascript
. In order for the function to register the double click and change the color of the box, I followed the model that comes in this tutorial:
https://www.w3schools.com/js/js_htmldom_eventlistener.asp
The code would look like this:
##Esto se ejecuta en otra celda
%%javascript
let boton = document.getElementById("boton");
boton.addEventListener("click", myf1);
boton.addEventListener("click", myf2);
boton.addEventListener("mouseover", function(){boton.textContent="¡Hola!"});
boton.addEventListener("mouseout", function(){boton.textContent="No te vayas"});
function myf1() {
document.getElementById("boton").style.backgroundColor= "red";
}
function myf2() {
document.getElementById("boton").style.backgroundColor = "blue";
}
Now when I return to the button, the color immediately changes to blue, i.e. it doesn't log the "red" then "blue" events on click. Considering that I am a beginner, I appreciate any guidance and also your understanding and patience.
The button registers the two functions. When the button is touched, this is what happens:
The events happen so quickly that the HTML doesn't have time to color it red.
If you want to see the change easily, change it like this:
With this function, the Javascript will wait up to 1000 milliseconds.
It's not quite clear what you meant by assigning the click event two functions. If what you wanted was that when you press the first time it changes to red and the second time it changes to blue, the way to achieve it has to be to manage that from a single function, which keeps track of how many times it was pressed. For example:
The weird syntax of putting all code inside curly braces
(function(){...})()
is a trick typically used in JavaScript to preventboton
o fromcontador
being global variables from "dirtying" the global namespace. Everything is defined inside an unnamed function, which immediately after being defined is executed. Conceptually it is equivalent to writing everything out, but this avoids having global variables.