JavaScript Functions – Change HTML Text and CSS
In this tutorial, we are going to change our CSS and HTML text using JavaScript functions dynamically. And also learn about arrow functions and a self-invoking anonymous function.
Changing HTML Text using JavaScript
Changing the text of web page or a particular part of a web page by invoking click event using JavaScript.
<html> <head> <title> JavaScript Function </title> <script> function func1(){ document.getElementById("divElement").innerHTML="Change Text"; } </script> </head> <body> <div id="divElement"> Text </div> <button onclick="func1()">Click </button> </body> </html>
In the above code, I have created a function named as func1() to target div element which has id as “divElement”. But function will call only when click event is happening.
At the starting web page look like this:
Output :
Text
After click event text will change to Change Text and output of web page look like as shown below.
Output:
Change Text
Changing CSS
Changing style sheet dynamically of elements or web page by invoking click event using JavaScript.
<html> <head> <title> JavaScript Function </title> <script> function func1(){ document.getElementById("divElement").style.color="blue"; } </script> </head> <body> <div id="divElement"> Text </div> Paragraph <button onclick="func1()">Click </button> </body> </html>
In the above code, using a function named as func1() I have change text color from black to blue by clicking the button. This event is done using function created under script tag. This func1() is executed only when the button is clicked by the user.
When we load the page then web page will look like this :
Output
Text
Paragraph
After click event occurs function func1() will execute and color of text change to blue. Since we have targeted only div tag using its id divElement, therefore, color will change to Text only.
Output:
Text
Paragraph
Other Functions in JavaScript
Self Invoking Anonymous Function: Anonymous function are the function which has no name.Functions which are executed at load time and have no name then this type of function known as a self-invoking anonymous function. Here in below code, I have created a function which will execute at load time and set variable x as HELLO.
Syntax : (function (){ var x ="HELLO"; })();
Arrow Function: Arrow function are also an anonymous function. Arrow function is used to deal with ambiguity generated by this keyword in JavaScript. It is an alternative of regular expression in JavaScript. Arrow Function cannot use as constructors.
In below code, I have created a function which return multiplication of x and y and this function is stored in constant variable x.
Syntax : const x = (x,y) => x*y;
Check out other blogs as well:
Create Smiley Emojis using HTML and CSS.
What is Div Tag and How nested Div Tag work in HTML and using CSS.
What is CSS and difference between CSS and CSS3
Leave a Reply