Main Content

HTML

HTML UI component

  • HTML UI component

Description

An HTML UI component allows you to embed HTML, JavaScript®, or CSS into your app and to interface with third-party JavaScript libraries. Use the HTML object to modify the appearance and behavior of an HTML UI component after you create it.

Creation

Create an HTML UI component in an app using the uihtml function.

Properties

expand all

HTML

HTML markup or file, specified as a character vector or string scalar that contains either HTML markup or the path to an HTML file. All HTML markup and files must be well formed. If the specified character vector or string scalar ends with .html, then it is assumed to be the path to an HTML file.

This table gives more information about each of the options.

HTML SourceExampleDetails
HTML markuph = uihtml("HTMLSource","<p>This is <span style="color:red">red</span> text.</p>")

Specify HTML markup if your content consists only of simple, formatted text, without any JavaScript code.

When you embed HTML markup, you do not need to specify <html> or <body> tags. If the markup you specify is supported in the Chromium browser used by MATLAB® figures created with the uifigure function, then it will render.

HTML fileh = uihtml("HTMLSource","CustomCharts.html")

Specify an HTML file if your HTML content contains any of these attributes:

  • Any JavaScript code

  • Supporting files, such as CSS, JavaScript, libraries, or images

  • Additional structure beyond a single string of markup

The HTML file must be located in a place that your local file system can access. Any supporting files must be located in the folder that contains the HTML file you specify for the HTMLSource property or in a subfolder of that folder. For more information, see Limitations.

MATLAB data, specified as any MATLAB data type. Use this argument when the value of HTMLSource is the path to an HTML file defining a JavaScript object. Then, this data can be synchronized between the MATLAB HTML UI component and the JavaScript object.

To synchronize the value of the Data property between MATLAB and the third-party content that you are embedding in your app, create a setup function in an HTML file that connects a JavaScript object called htmlComponent to the HTML UI component in MATLAB. Then, set the HTMLSource property value to the path to the file.

Changes in the value of the Data property trigger callback events in only one direction. Specifically,

  • When the Data property is set in MATLAB, the Data property of the htmlComponent JavaScript object also updates and triggers JavaScript event listeners of the 'DataChanged' event.

  • When htmlComponent.Data is set in JavaScript, the Data property of the HTML UI component in MATLAB also updates and triggers the DataChangedFcn callback.

If you have data like nested cell arrays, arrays of structures, or MATLAB table array data, you might need more information about how data is converted between MATLAB and JavaScript. When the Data property of an HTML UI component is set in MATLAB, the data is converted using the jsonencode function, synchronized with JavaScript, parsed using JSON.parse(), and finally set to the Data property of the htmlComponent JavaScript object. Conversions happen in the opposite direction as well by way of JSON.stringify() and the jsondecode function. The Data property is the only property that synchronizes with JavaScript.

Refer to the jsonencode function for more information about the data types it supports. If the jsonencode function does not support your data type, then use a data type conversion function, like num2str, to convert your data to a supported type. Then, set it as the value of the Data property.

For more information about how to write an HTML file that enables data synchronization and the properties of the htmlComponent JavaScript object, see Create HTML Content in Apps.

Interactivity

State of visibility, specified as 'on' or 'off', or as numeric or logical 1 (true) or 0 (false). A value of 'on' is equivalent to true, and 'off' is equivalent to false. Thus, you can use the value of this property as a logical value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

  • 'on' — Display the object.

  • 'off' — Hide the object without deleting it. You still can access the properties of an invisible UI component.

To make your app start faster, set the Visible property to 'off' for all UI components that do not need to appear at startup.

Tooltip, specified as a character vector, cell array of character vectors, string array, or 1-D categorical array. Use this property to display a message when the user hovers the pointer over the component at run time. The tooltip displays even when the component is disabled. To display multiple lines of text, specify a cell array of character vectors or a string array. Each element in the array becomes a separate line of text. If you specify this property as a categorical array, MATLAB uses the values in the array, not the full set of categories.

Context menu, specified as a ContextMenu object created using the uicontextmenu function.

Note

This property has no effect when the HTMLSource property of the HTML UI component is set. Instead, to display a context menu when a user right-clicks on the component, detect the event and write code to programmatically open a context menu in the expected location.

Example: Open Context Menu for HTML UI Component

Create an HTML file called cmexample.html. In the file:

  • Create a <div> element that makes up the component appearance.

  • Write a setup function to connect the htmlComponent JavaScript object to the HTML UI component in MATLAB.

  • Add an event listener in the setup function that listens for a contextmenu event (such as a right-click) on the JavaScript object and creates a listener callback function. When a contextmenu event occurs, the listener callback sets the Data property of the htmlComponent object to store the action that triggered the event and the position at which the event was triggered. This data is then available from the associated MATLAB HTML UI component.

<!DOCTYPE html> 
<html> 
<body> 

<div id="contextMenuTarget" style="background-color:gray;width:200px;height:200px;">
    Right-click on this component to open a context menu.
</div>

<script type="text/javascript">
    function setup(htmlComponent) {
        document.getElementById("contextMenuTarget").addEventListener("contextmenu", function(event) {
            htmlComponent.Data = {Action:"showContextMenu", PosData:[event.clientX, event.clientY]};
        });
    }
</script>

</body> 
</html>

In a MATLAB script, create an HTML UI component and a context menu object in a UI figure. Specify the cmexample.html file as the HTMLSource property of the HTML UI component. Then, define a callback function named openContextMenu that takes the context menu as input, and that is executed whenever the Data property of the HTML UI component changes. In the callback function, check whether the event that triggered the callback execution was a context menu event. If so, retrieve the position of the event and use that to open the context menu in the expected location in the figure.

fig = uifigure;

h = uihtml(fig,"HTMLSource","cmexample.html");
h.Position = [100 100 200 200];

cm = uicontextmenu(fig);
m1 = uimenu(cm,"Text","Option 1");
m2 = uimenu(cm,"Text","Option 2");
h.ContextMenu = cm;

h.DataChangedFcn = {@openContextMenu,cm};

function openContextMenu(src,event,cm)
    switch src.Data.Action
        case "showContextMenu"
            p = getpixelposition(src,true);
            xClick = src.Data.PosData(1);
            yClick = src.Data.PosData(2);
            xOpen = p(1)+xClick;
            yOpen = p(2)+p(4)-yClick;
            open(cm,xOpen,yOpen);
    end
end

Run the script and right-click on the HTML UI component to open the context menu.

HTML UI component inside a UI figure window. The HTML UI component contains text that says: "Right-click on this component to open a context menu." There is a context menu open on the component.

Position

Location and size of HTML UI component relative to the parent container, specified as a four-element vector of the form [left bottom width height]. This table describes each element in the vector.

ElementDescription
leftDistance from the inner left edge of the parent container to the outer left edge of the HTML UI component
bottomDistance from the inner bottom edge of the parent container to the outer bottom edge of the HTML UI component
widthDistance between the right and left outer edges of the HTML UI component
heightDistance between the top and bottom outer edges of the HTML UI component

The Position values are relative to the drawable area of the parent container. The drawable area is the area inside the borders of the container and does not include the area occupied by decorations such as a menu bar or title.

All measurements are in pixel units.

Inner location and size of HTML UI component, specified as a four-element vector of the form [left bottom width height]. All measurements are in pixel units. This property value is identical to the Position property.

This property is read-only.

Outer location and size of HTML UI component, returned as a four-element vector of the form [left bottom width height]. All measurements are in pixel units. This property value is identical to the Position property.

Layout options, specified as a GridLayoutOptions object. This property specifies options for components that are children of grid layout containers. If the component is not a child of a grid layout container (for example, it is a child of a figure or panel), then this property is empty and has no effect. However, if the component is a child of a grid layout container, you can place the component in the intended row and column of the grid by setting the Row and Column properties of the GridLayoutOptions object.

For example, this code places an HTML UI component in the third row and second column of its parent grid.

g = uigridlayout([4 3]);
h = uihtml(g);
h.HTMLSource = '<body style="background-color:powderblue;"><p>Hello World!</p></body>';
h.Layout.Row = 3;
h.Layout.Column = 2;

To make the HTML UI component span contiguous rows or columns, specify the Row or Column property as a two-element vector. For example, this HTML UI component spans columns 2 through 3.

h.Layout.Column = [2 3];

Callbacks

Callback when data changes, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle. Subsequent elements in the cell array are the arguments to pass to the callback function.

  • Character vector containing a valid MATLAB expression (not recommended). MATLAB evaluates this expression in the base workspace.

When the value of the Data property changes in the htmlComponent JavaScript object, the Data property of the MATLAB HTML UI component is updated, and this callback executes.

This callback function can access specific information about changes in data in the JavaScript object. MATLAB passes the information in a DataChangedData object as the second argument to your callback function. In App Designer, the argument is called event. You can query the DataChangedData object properties using dot notation. For example, event.PreviousData returns the previous value of Data before it was last updated or changed. The DataChangedData object is not available to callback functions specified as character vectors.

This table lists the properties of the DataChangedData object.

PropertyDescription
DataMost recent data resulting from the last DataChanged event
PreviousDataData before the last DataChanged event
Source

MATLAB HTML UI component that executes the callback

EventName'DataChanged'

For more information about writing callbacks, see Callbacks in App Designer.

Since R2023a

Callback when an event is received from the HTML source, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle. Subsequent elements in the cell array are the arguments to pass to the callback function.

  • String scalar or character vector containing a valid MATLAB expression (not recommended). MATLAB evaluates this expression in the base workspace.

This callback executes when an event is sent from JavaScript to MATLAB by calling the sendEventToMATLAB function on the JavaScript htmlComponent object. Use this callback to write MATLAB code to respond to user interaction or changes in the HTML component, such as a click on a button HTML element. For more information, see Create HTML Content in Apps.

This callback function can access specific information about the event that the JavaScript object sent. MATLAB passes the information in an HTMLEventReceivedData object as the second argument to your callback function. In App Designer, the argument is called event. Query the HTMLEventReceivedData object properties using dot notation. For example, event.HTMLEventName returns name of the event that was specified by the JavaScript object. The HTMLEventReceivedData object is not available to callback functions specified as string scalars or character vectors.

This table lists the properties of the HTMLEventReceivedData object.

PropertyDescription
HTMLEventNameName of the event as specified by the sendEventToMATLAB function called in the JavaScript code
HTMLEventDataEvent data as specified by the sendEventToMATLAB function called in the JavaScript code
Source

MATLAB HTML UI component that executes the callback

EventName'HTMLEventReceived'

For more information about writing callbacks, see Create Callbacks for Apps Created Programmatically.

Object creation function, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle. Subsequent elements in the cell array are the arguments to pass to the callback function.

  • Character vector containing a valid MATLAB expression (not recommended). MATLAB evaluates this expression in the base workspace.

For more information about specifying a callback as a function handle, cell array, or character vector, see Callbacks in App Designer.

This property specifies a callback function to execute when MATLAB creates the object. MATLAB initializes all property values before executing the CreateFcn callback. If you do not specify the CreateFcn property, then MATLAB executes a default creation function.

Setting the CreateFcn property on an existing component has no effect.

If you specify this property as a function handle or cell array, you can access the object that is being created using the first argument of the callback function. Otherwise, use the gcbo function to access the object.

Object deletion function, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle. Subsequent elements in the cell array are the arguments to pass to the callback function.

  • Character vector containing a valid MATLAB expression (not recommended). MATLAB evaluates this expression in the base workspace.

For more information about specifying a callback as a function handle, cell array, or character vector, see Callbacks in App Designer.

This property specifies a callback function to execute when MATLAB deletes the object. MATLAB executes the DeleteFcn callback before destroying the properties of the object. If you do not specify the DeleteFcn property, then MATLAB executes a default deletion function.

If you specify this property as a function handle or cell array, you can access the object that is being deleted using the first argument of the callback function. Otherwise, use the gcbo function to access the object.

Callback Execution Control

Callback interruption, specified as 'on' or 'off', or as numeric or logical 1 (true) or 0 (false). A value of 'on' is equivalent to true, and 'off' is equivalent to false. Thus, you can use the value of this property as a logical value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

This property determines if a running callback can be interrupted. There are two callback states to consider:

  • The running callback is the currently executing callback.

  • The interrupting callback is a callback that tries to interrupt the running callback.

MATLAB determines callback interruption behavior whenever it executes a command that processes the callback queue. These commands include drawnow, figure, uifigure, getframe, waitfor, and pause.

If the running callback does not contain one of these commands, then no interruption occurs. MATLAB first finishes executing the running callback, and later executes the interrupting callback.

If the running callback does contain one of these commands, then the Interruptible property of the object that owns the running callback determines if the interruption occurs:

  • If the value of Interruptible is 'off', then no interruption occurs. Instead, the BusyAction property of the object that owns the interrupting callback determines if the interrupting callback is discarded or added to the callback queue.

  • If the value of Interruptible is 'on', then the interruption occurs. The next time MATLAB processes the callback queue, it stops the execution of the running callback and executes the interrupting callback. After the interrupting callback completes, MATLAB then resumes executing the running callback.

Note

Callback interruption and execution behave differently in these situations:

  • If the interrupting callback is a DeleteFcn, CloseRequestFcn, or SizeChangedFcn callback, then the interruption occurs regardless of the Interruptible property value.

  • If the running callback is currently executing the waitfor function, then the interruption occurs regardless of the Interruptible property value.

  • If the interrupting callback is owned by a Timer object, then the callback executes according to schedule regardless of the Interruptible property value.

Note

When an interruption occurs, MATLAB does not save the state of properties or the display. For example, the object returned by the gca or gcf command might change when another callback executes.

Callback queuing, specified as 'queue' or 'cancel'. The BusyAction property determines how MATLAB handles the execution of interrupting callbacks. There are two callback states to consider:

  • The running callback is the currently executing callback.

  • The interrupting callback is a callback that tries to interrupt the running callback.

The BusyAction property determines callback queuing behavior only when both of these conditions are met:

  • The running callback contains a command that processes the callback queue, such as drawnow, figure, uifigure, getframe, waitfor, or pause.

  • The value of the Interruptible property of the object that owns the running callback is 'off'.

Under these conditions, the BusyAction property of the object that owns the interrupting callback determines how MATLAB handles the interrupting callback. These are possible values of the BusyAction property:

  • 'queue' — Puts the interrupting callback in a queue to be processed after the running callback finishes execution.

  • 'cancel' — Does not execute the interrupting callback.

This property is read-only.

Deletion status, returned as an on/off logical value of type matlab.lang.OnOffSwitchState.

MATLAB sets the BeingDeleted property to 'on' when the DeleteFcn callback begins execution. The BeingDeleted property remains set to 'on' until the component object no longer exists.

Check the value of the BeingDeleted property to verify that the object is not about to be deleted before querying or modifying it.

Parent/Child

Parent container, specified as a Figure object created using the uifigure function, or one of its child containers: Tab, Panel, ButtonGroup, or GridLayout. If no container is specified, MATLAB calls the uifigure function to create a new Figure object that serves as the parent container.

Visibility of the object handle, specified as 'on', 'callback', or 'off'.

This property controls the visibility of the object in its parent's list of children. When an object is not visible in its parent's list of children, it is not returned by functions that obtain objects by searching the object hierarchy or querying properties. These functions include get, findobj, clf, and close. Objects are valid even if they are not visible. If you can access an object, you can set and get its properties, and pass it to any function that operates on objects.

HandleVisibility ValueDescription
'on'The object is always visible.
'callback'The object is visible from within callbacks or functions invoked by callbacks, but not from within functions invoked from the command line. This option blocks access to the object at the command-line, but allows callback functions to access it.
'off'The object is invisible at all times. This option is useful for preventing unintended changes to the UI by another function. Set the HandleVisibility to 'off' to temporarily hide the object during the execution of that function.

Identifiers

This property is read-only.

Type of graphics object, returned as 'uihtml'.

Object identifier, specified as a character vector or string scalar. You can specify a unique Tag value to serve as an identifier for an object. When you need access to the object elsewhere in your code, you can use the findobj function to search for the object based on the Tag value.

User data, specified as any MATLAB array. For example, you can specify a scalar, vector, matrix, cell array, character array, table, or structure. Use this property to store arbitrary data on an object.

If you are working in App Designer, create public or private properties in the app to share data instead of using the UserData property. For more information, see Share Data Within App Designer Apps.

Object Functions

sendEventToHTMLSourceSend HTML UI component event from MATLAB to JavaScript

Examples

collapse all

Create an HTML component and display formatted text in it using HTML markup.

fig = uifigure('Position',[561 497 333 239]);
h = uihtml(fig);
h.HTMLSource = '<p style="font-family:arial;"><b><span style="color:red;">Hello</span> <u>World</u>!</b></p>';

Create an HTML file to embed audio and video elements in your app and reference media source files.

First, create an empty HTML UI component in a figure.

fig = uifigure;
fig.Position = [500 500 380 445];

h = uihtml(fig);
h.Position = [10 10 360 420];

Then, create an HTML file called audio_videoplayers.html. In the file, add audio and video elements and specify their file sources relative to the path of the HTML file. In this example, the media files are in the same directory as the HTML file.

A good practice is to specify multiple file sources for each element because not all contexts support the same file types. For example, MP4 videos are not supported for HTML components in the MATLAB Desktop but are supported in MATLAB Online™. In the video element, specify an OGA file as the first video for the app to try to play. Then, specify an MP4 file as a fallback if the first file is not supported.

<!DOCTYPE html>
<html>
	<body style="background-color:white;font-family:arial;">
		<p style="padding-left:20px">
		Play audio file:
		</p>
		
		<audio controls style="padding-left:20px">
			<source src="./handel_audio.wav" type="audio/wav">
			<source src="./handel_audio.oga" type="audio/ogg">
			Your browser does not support the audio tag.
		</audio>
		
		<p style="padding-left:20px">
		Play video file:
		</p>
		
		<video width="320" height="240" controls style="padding-left:20px">
                        <source src="./xylophone_video.oga" type="video/ogg">
			<source src="./xylophone_video.mp4" type="video/mp4">
			Your browser does not support the video tag.
		</video>
		
	</body>
</html>

Now, embed the HTML file in your app by setting the HTMLSource property to the full path to the file.

h.HTMLSource = fullfile(pwd,'audio_videoplayers.html');

Create an htmlComponent JavaScript® object that displays the data that is set on an HTML UI component in MATLAB®.

First, create an empty HTML UI component and position it within a figure.

fig = uifigure;
fig.Position = [500 500 490 180];

h = uihtml(fig);
h.Position = [20 20 450 130];

Then, create an HTML file called displayDataFromMATLAB.html. In the file,

  • Use a style tag to define internal CSS styles for the <div> elements that display text.

  • Write a setup function inside of a <script> tag to connect your JavaScript object, called htmlComponent, to the HTML UI component you created in MATLAB.

  • Add an event listener within the setup function. The event listener listens for "DataChanged" events on the htmlComponent JavaScript object and creates a listener callback function. When a "DataChanged" event occurs, the listener callback function updates the "dataDisplay" <div> element with the value that is set to the Data property in MATLAB.

<!DOCTYPE html>
<html>
<head>
<style>
#prompt {
  font-family: sans-serif;
  text-align:center;
  border-radius: 5px;
  background-color: lightblue;
  padding: 20px;
}

#dataDisplay {
  border-radius: 5px;
  height: 10vh;
  padding: 12px 20px;
}
</style>

<script type="text/javascript">
         
        function setup(htmlComponent) {
		          
            htmlComponent.addEventListener("DataChanged", function(event) {
            document.getElementById("dataDisplay").innerHTML = htmlComponent.Data;
            });     
        }
</script>
</head>

<body>
     <div id="prompt">
		
	<span><label for="prompt"><strong>Data from MATLAB will display here:</strong></label></span>
	<br/><br/>
	<div id ="dataDisplay">
	Please set data in MATLAB...
	</div>
		
     </div>
</body>

</html>

Now, in MATLAB, set the value of the HTMLSource property to the path to the HTML file.

h.HTMLSource = fullfile(pwd,'displayDataFromMATLAB.html');

Set the value of the Data property for the HTML UI component. Notice how the htmlComponent JavaScript object updates in your HTML UI component.

h.Data = "Hello World!";

Create a JavaScript htmlComponent object that shows a button and a progress bar, and display the current progress in the MATLAB Command Window whenever the progress changes.

First, create an empty HTML UI component and position it within a figure.

fig = uifigure("Position",[500 500 350 150]);
h = uihtml(fig,"Position",[50 40 250 70]);

Then, create an HTML file named progressBar.html. In the file:

  • Use a <style> tag to define internal CSS styles for a button and a progress bar element.

  • Write a setup function inside of a <script> tag to connect your JavaScript object, named htmlComponent, to the HTML UI component you created in MATLAB.

  • Add an event listener within the setup function. The event listener listens for "click" events on the button and creates a listener callback function. When a user clicks the Next button, the listener callback function updates the progress bar and sets the Data property of the htmlComponent to the new progress value.

<!DOCTYPE html>
<html>
<head>
<style>
body {
    text-align: center;
}
button {
    width: 43px;
    height: 20px;
}
progress {
    width: 90%;
    height: 20px;
}
</style>

<script type="text/javascript">      
    function setup(htmlComponent) {
        let btn = document.getElementById("nextButton");
        htmlComponent.Data = 0;
        btn.addEventListener("click", function(event) {
            let progress = htmlComponent.Data;
            progress = Math.min(progress+25,100);
            document.getElementById("progressBar").value = progress;
            htmlComponent.Data = progress;
        }); 
    }
</script>
</head>

<body>
    <button id="nextButton">Next</button>
    <br>
    <progress id="progressBar" value="0" max="100"></progress> 
</body>	
</html>

In MATLAB, set the value of the HTMLSource property to the path of the HTML file. Create a DataChangedFcn callback function that displays the updated progress whenever the Data property changes.

h.HTMLSource = "progressBar.html";
h.DataChangedFcn = @(src,event)disp(event.Data);

HTML UI component. The component contains a button with the text "Next" above a progress bar.

Click the Next button to update the progress bar and change the Data property. The progress displays in the MATLAB Command Window.

Since R2023a

Create a JavaScript htmlComponent object that generates a random number when a user clicks a button, and display the number in MATLAB.

First, create a new script named myRandomNum.m. In the script, create an empty HTML UI component and position it within a figure.

fig = uifigure("Position",[100 100 300 160]);
h = uihtml(fig,"Position",[50 50 200 60]);

Then, create an HTML file named generateJSRandomNumber.html. In the file:

  • Use a <style> tag to define internal CSS styles for a button element.

  • Write a setup function inside of a <script> tag to connect your JavaScript object, named htmlComponent, to the HTML UI component you created in MATLAB.

  • Add an event listener within the setup function that listens for "click" events on the button. When a user clicks the button, first generate a random number, and then send an event to notify MATLAB of the click. Pass in the random number as event data so that you can access the number in MATLAB.

<!DOCTYPE html>
<html>
<head>
<style>
body {
  height: 100%;
  text-align: center
}

button {
  width: 100%;
  height: 100%;
  background-color: white;
  color: black;
  border: 3px solid blue;
  font-size: 12px;
  cursor: pointer;
}
</style>

<script type="text/javascript">      
   function setup(htmlComponent) {           
       let button = document.getElementById("Button");
       button.addEventListener("click", function(event) {
           let num = Math.floor(Math.random() * 100) + 1;
           htmlComponent.sendEventToMATLAB("ButtonClicked",num);
       });
   }
</script>
</head>

<body>
   <button id="Button">Generate Random Number</button> 
</body>	
</html>

In MATLAB, in the myRandomNum.m script, set the value of the HTMLSource property to the path of the HTML file. Create an HTMLEventReceivedFcn callback function that displays the generated random number in the Command Window.

h.HTMLSource = "generateJSRandomNumber.html";
h.HTMLEventReceivedFcn = @displayNumber;

function displayNumber(src,event)
name = event.HTMLEventName;
if strcmp(name,'ButtonClicked')
    number = event.HTMLEventData;
    disp(number);
end
end

Run the script and click the button to generate and display the random number in the MATLAB Command Window.

Button with a blue border and text "Generate Random Number"

Since R2023a

Create a JavaScript htmlComponent object that updates HTML element styling when a user interacts with a MATLAB knob component.

First, create a new script named myTemperature.m. In the script, create a knob UI component and an empty HTML UI component in a UI figure.

fig = uifigure;
k = uiknob(fig,"discrete", ...
    "Items",["Freezing","Cold","Warm","Hot"], ...
    "ItemsData",[0 1 2 3], ...
    "Value",0);
h = uihtml(fig,"Position",[230 60 40 150]);

Then, create an HTML file named thermometer.html. In the file:

  • Use a <style> tag to define internal CSS styles for the parts of a thermometer.

  • Write a setup function inside of a <script> tag to connect your JavaScript object, named htmlComponent, to the HTML UI component you created in MATLAB.

  • Add an event listener within the setup function that listens for events from MATLAB named "TemperatureChanged". When the htmlComponent object is notified that the temperature has changed, query the event data to get the new temperature. Then, adjust the styling on the thermometer to reflect the new temperature.

<!DOCTYPE html>
<html>
<head>
<style>
.bulb {
    width: 30px;
    height: 30px;
    border: 2px solid;
    border-radius: 50%;
    background-color: red;
}

.stem {
    width: 10px;
    height: 30px;
    border-top: 2px solid;
    border-left: 2px solid;
    border-right: 2px solid;
    position: relative;
    left: 10px;
    top: 4px;
    background-color: white;
}

.stem.hot {
    background-color: red;
}
</style>

<script type="text/javascript">      
    function setup(htmlComponent) {           
        htmlComponent.addEventListener("TemperatureChanged", function(event) {
            let stem1 = document.getElementById("Stem1");
            let stem2 = document.getElementById("Stem2");
            let stem3 = document.getElementById("Stem3");
            (event.Data > 0) ? stem1.classList.add("hot") : stem1.classList.remove("hot");
            (event.Data > 1) ? stem2.classList.add("hot") : stem2.classList.remove("hot");
            (event.Data > 2) ? stem3.classList.add("hot") : stem3.classList.remove("hot");
        });
    }
</script>
</head>

<body>
    <div id="Stem3" class="stem"></div>
    <div id="Stem2" class="stem"></div> 
    <div id="Stem1" class="stem"></div> 
    <div id="Bulb" class="bulb"></div>
</body>	
</html>

In MATLAB, in the script, write code to communicate with the HTML source:

  • Set the value of the HTMLSource property of the HTML UI component to the path of the HTML file.

  • Write a ValueChangedFcn callback function for the knob that sends an event named "TemperatureChanged" to the HTML source when the temperature changes. Pass the new temperature value as event data.

h.HTMLSource = "thermometer.html";
k.ValueChangedFcn = @(src,event) handleKnobValueChanged(src,event,h);

function handleKnobValueChanged(src,event,h)
val = src.Value;
sendEventToHTMLSource(h,"TemperatureChanged",val);
end

Run the script and interact with the knob to update the thermometer.

Knob pointing to "Warm" and a corresponding thermometer

Create an HTML UI component that displays data with multiple fields.

Create an item card component that lists an item name, price, and quantity. Design the HTML UI component to take in the item data as a struct in MATLAB. First, check how struct data is encoded when the data is transferred from MATLAB to JavaScript by using the jsonencode function.

matlabData = struct("ItemName","Apple","Price",2,"Quantity",10);
jsonencode(matlabData)
ans = 
'{"ItemName":"Apple","Price":2,"Quantity":10}'

For more information about how HTML components transfer data between MATLAB and JavaScript, see Create HTML Content in Apps.

Next, create an HTML source file called itemCard.html that creates and styles the item card HTML component. In the file:

  • Use a <style> tag to define internal CSS styles for an item card.

  • Write a setup function inside of a <script> tag to detect when the Data property of the MATLAB HTML UI component object changes, and then access the Data property of the JavaScript htmlComponent object. The data is encoded as a JavaScript object with multiple properties. Access these properties to update the content of the HTML component.

  • Use a <body> tag to create the main HTML document content.

<!DOCTYPE html>
<html>
<head>
<style>
    table {
        border: 2px solid;
        border-spacing: 0;
        text-align: center;
        position: absolute;
        width: 100%;
        height: 100%;
        margin: 0px;
        padding: 0px;
    }
    th {
        background-color: #097A7A;
        color: black;
        font-size: 24px;
        height: 40%;
    }
    tr {
        background-color: #98D6D6;
        color: gray;
        height: 30%;
    }
    td {
        padding: 5px;
    }
</style>

<script type="text/javascript">       
    function setup(htmlComponent) {
        htmlComponent.addEventListener("DataChanged", function(event) {
            let table = document.getElementById("itemCard");
            table.rows[0].cells[0].innerHTML = htmlComponent.Data.ItemName;
            table.rows[1].cells[1].innerHTML = htmlComponent.Data.Price;
            table.rows[2].cells[1].innerHTML = htmlComponent.Data.Quantity;
        });     
    }
</script>
</head>

<body>
    <div>
	<table id="itemCard">
            <tr>
                <th colspan="2">Item</th>
            </tr>
            <tr>
                <td>Price:</td>
                <td></td>
            </tr>
            <tr>
                <td>Quantity:</td>
                <td></td>
            </tr>
        </table>
    </div>
</body>
</html>

Create an HTML component in a UI figure. Specify itemCard.html as the HTML source and an item data struct as the component data.

itemData = struct("ItemName","Apple","Price",2,"Quantity",10);
fig = uifigure;
c = uihtml(fig,"HTMLSource","itemCard.html","Data",itemData);

HTML component item card with header "Apple" and items "Price: 2" and "Quantity: 10"

Version History

Introduced in R2019b

expand all