Velo Tutorial: Hiding a Video Player When There Is No Video to Play
If you'd rather not have any video play, you can automatically hide the Video Player when the item in your collection has no URL. This tutorial shows you how to do this using Velo.
This tutorial has 2 parts:
- Instructions on how to get set up, including code you can copy and paste onto your page
- An explanation of what each line of code does
Instructions
- Add a dataset to your page and connect it to your collection.
- Add a Video Player and connect it to the URL field.
- Open the Code panel of your page (you can just drag it up from the bottom). You can delete the default code that appears there.
- Copy the code below and paste it in the page's tab in the Code panel.
1$w.onReady(() => {
2 $w("#myDataset").onReady(() => {
3 // Gets the current item properties and stores them in a variable called item
4 const item = $w("#myDataset").getCurrentItem();
5 // Checks if the current item has a value in the "video" field
6 if (!item.video) {
7 // Collapses the video player if there is no value for "video"
8 $w("#videoPlayer").collapse();
9 }
10 });
11});
- Make sure to make these replacements:
- #myDataset: the ID of the dataset (hover over it to see its ID)
- video: the field key of the field in your collection that stores the video URL
- #videoPlayer: the ID of the video player (hover over it to see its ID)
- Preview your page for an item that does not have a URL and check that the video player is not displayed.
Understanding the Code
Line 1 calls the onReady()
function. This defines the code that will run when the page is finished loading.
$w.onReady(() => {
Line 2 calls the dataset onReady()
function. This defines the code that will run after the dataset has loaded all the information for the current item.
$w("#myDataset").onReady(() => {
Line 4 defines a variable called item
and then sets its value to be the object returned by the getCurrentItem()
function.
const item = $w("#myDataset").getCurrentItem();
This object contains the properties (fields) in the current item and their respective values. When a given field is blank in the current item, the object does not contain the corresponding property.
Line 6 checks to see if the item
variable from the previous line includes the video
field, which is the field in the collection that stores the video URL.
if (!item.video) {
If the current item's video
field is empty, then that field is not included in the object that was returned by getCurrentItem
in the previous line.
Line 8 collapses the video player if the video
field is blank.
$w("#videoPlayer").collapse();
If the video
field is not blank, then this line does not run. The video player remains visible to show the video at the URL defined in your collection for this item.
You could also use the hide()
function to hide the video player instead of collapsing it.