Home Examples Docs
10. Loading images
This section explains how to load images in TargetJS.
In the first example, we demonstrate a basic way to display an image. We change the element to 'img', as the default is 'div'. Next, we specify the src target, which sets the src attribute of the image. Finally, we set the desired height, while the width is adjusted automatically based on the image’s dimensions.
In the second example, we preload the image before displaying it. Initially, we keep the element set to the default value of 'div'. We also style the backgroundColor and set the text content to 'loading'. Using fetchImage(), we fetch the image and store it in the browser cache. When the image is loaded, updateElement is executed to switch the element to an img tag. Then, fadeIn is executed to smoothly adjust the width and opacity. Note that updateElement runs only after the image has loaded, and similarly, fadeIn is executed only after updateElement has completed.
In the next example, we create a simple image gallery that displays a new image every second from a set of two images. As you can see, HTML attributes and tags are all treated as targets, providing a fluid and unified way of updating content. We morph the default div element into an img element, then smoothly fade its opacity