Toggling between 2 images is very common on the web.
An example of this is a like button, which can be seen on many sites such as youtube and facebook.
At first, for a user, the button is unlit. After clicking on it, the button then lights up, showing that the user has liked the video or the post.
This is demonstrated below.
It almost has applications for things such as online text editors that have buttons such as making the text bold, italic, or underlined. When you click on these buttons, it's good to highlight them to show that they're selected.
So how do we do this in code?
Below is the source code for creating the like button shown above.
Just like with many things with programming, there are many ways of doing it.
The way done in this example is simple enough, so it's probably a good way of doing it.
The HTML code an image within a label tag.
What we're really is doing is changing images from one to the other, back and forth, with clicks (click events).
This img element within this label has a number of attributes.
We want the image to show a pointer when a user hovers over it, so we give it the attribute, style="cursor:pointer"
Next, we give the button a class. This is important because we want target both images with a class. An id is unique to an element. A class is not. A class can be comprised of several elements. We want to give both like button images, unclicked and clicked, to be of the same class, so that we can target both images. The way we will distinguish them is by the custom data-status attribute we create next. You can always use custom attributes or id attributes to distinguish members of a class.
The data-status attribute will be "unclicked" for the unclicked like image and "clicked" for the clicked like image.
So this function is triggered with the click event.
We target any elements with the class of "likebutton", which are the 2 like button images, one unclicked and the other clicked.
Within this function, we create a variable, clickedstatus, which gets the data-status attribute.
If the status is clicked, then we change it to the unclicked like button image. If not, we change it to the clicked like button image.
This is not the only way of doing it but a good, effective, simple way of doing it.