Зміст курсу
HTML & JavaScript Interactivity for Beginners
HTML & JavaScript Interactivity for Beginners
Changing the Styles of HTML Elements
In the last chapter, you learned how to find an HTML and change its content. Likewise, you can change the styles of the HTML. We'll look at several ways.
Change with Style Property
You can change the CSS style properties using the style
attribute of HTML Elements. Let's dive into an example right away. In the below code, the Javascript changes the font color of the paragraph tags to blue.
index
index
index
Note that you can access the above element either with the getElementById
or querySelector
. So through the style
attribute, you can change the value of any CSS property.
Change with Events
In the real world, most web applications change their styles after the occurrence of an event. So in this example, you'll discover how to hide an element using one button click and then make it visible again with another button click. This is possible with the help of the visibility
property.
Also, at this stage, do not pay much attention to the event part, as there'll be a separate lesson on it later. For now, assume that onclick
detects the click event of the button where you can write JavaScript code.
index
index
index
Changing Multiple CSS Properties at Once
You may arise with a scenario where you would have to change more than one style. Then from what you've learned so far, you can repeat the style
property with different values in each line.
However, it is not a best practice for coding as it needs to be readable. So then, you can create a JavaScript variable and store all the style values. Then when the button is clicked, you can associate the click event handler to the function to assign the variable mentioned above which is called template literals. Finally, you can assign it to the cssText
property.
index
index
index
Дякуємо за ваш відгук!