Hi Anvil. I am trying to implement the following:
- highlight text in the text area.
- trigger an alert window showing the text highlighted once the mouse is released.
I have tried insert this code in standard-page.html
document.addEventListener(‘mouseup’, function() {
var selection = window.getSelection();
var selectedText = selection.toString().trim();
}
But I have no idea how to pass the selectedText to Form1. I wanted to get this variable’s value because I need to show it as text in the alert window.
I have tried call_js() in the form but not sure what should be parameter.
Been struggling on this for a very long time. Really appreciate the help.
You really want your Javascript callback functions to be in Python. Anvil’s Javascript bridge allows you to do all your code in Python. For example, you can import anvil.js
in your form and work with anvil.js.window
and anvil.js.window.document
. Passing in a Python function as the event listener is easy, something like:
anvil.js.window.document.addEventListender('mouseup', self.mouseup_listener)
def mouseup_listener (self, **e):
selection = anvil.js.window.getSelection()
and so on. At that point you’re in your form and can access all your form elements. You sometimes need to play with the arguments to the functions used as Javascript callbacks (why I used a catchall argument, you can print(e)
to see what’s being passed in).
All of that is untested, but you can look through the docs and experiment with it to get it working. The above is the way I do all my Javascript interactions, even with third-party Javascript libraries.
2 Likes
Thanks for the suggestion. I have tried it. But got this error:
AttributeError: ‘HTMLDocument’ object has no attribute ‘addEventListender’
Probably because it needs addEventListener not Listender.
Also moved your method to be a proper instance method and added a needed second positional prop
2 Likes
As I said, untested code to be used as a basis for experimentation. I don’t know why, but that particular typo shows up a lot in my code.
1 Like
Thank you! Now I don’t have any errors. But e is just {} and selection is " < Selection proxyobject >".
How can I access the string text?
Did you use that code from your original Javascript? That still needs to be in your Python code.
1 Like
Thank you! I finally got it to work with selection.toString() without the trim()!