How to Select Highlighted Text in a Rich Text Input Using Custom JavaScript in WeWeb
Set up the Rich Text Input:
- Add a rich text input to your page.
Create a Workflow:
Go to the workflow section for your rich text input.
Add a new workflow and give it a name.
Set the trigger to "On Click".
Add Custom JavaScript:
In the workflow, choose "Custom JavaScript" as the action.
Enter the following code:
return window.getSelection().toString().trim()
This code selects the highlighted text when clicked.
Create a Variable:
Go to the variables section of your project.
Create a new variable (e.g., "selectedTextDemo").
Set the variable type to "Text".
Enable "Preserve on navigation" if you want the selected text to persist between page loads.
Update the Variable:
In your "Workflow" on the rich text input, add another action after the Custom JavaScript.
Choose "Update variable value".
Select your newly created variable (e.g., "selectedTextDemo").
Set its value to the result of the Custom JavaScript action.
Display the Selected Text (Optional):
Add a heading element to your page.
In the heading's properties, go to the "Text" section.
Bind the text to your variable (e.g., "selectedTextDemo"). This will display the selected text in real-time.
Copy to Clipboard (Optional):
In your workflow, add a "Copy to clipboard" action after updating the variable.
Set the content to copy as your variable (e.g., "selectedTextDemo").
Test Your Implementation:
Preview your page.
Type some text in the rich text input.
Highlight a portion of the text and click on it.
The selected text should appear in the heading (if you added one).
The selected text should also be copied to your clipboard.
By following these steps, you've created a system that selects highlighted text in a rich text input, stores it in a variable, optionally displays it on the page, and copies it to the clipboard - all without writing complex code - just one line of javascript.
Subscribe to my newsletter
Read articles from Daniel Migizi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Daniel Migizi
Daniel Migizi
π€Όπ¨π»βπ» Retired athlete turned Product Engineer, passionate about building on the web using Visual Development tools and AI.