JavaScript Example

javascript-find-function-example.jpg



javascript
// JavaScript function to calculate the area of a rectangle function calculateRectangleArea(length, width) { return length * width; } // Example usage of the function const length = 5; // Length of the rectangle const width = 3; // Width of the rectangle const area = calculateRectangleArea(length, width); // Calling the function with provided length and width console.log("The area of the rectangle with length " + length + " and width " + width + " is: " + area); Output the calculated area

Explanation:

  • This code defines a JavaScript function calculateRectangleArea that computes the area of a rectangle based on its length and width.
  • Inside the function, it multiplies the length and width parameters to get the area, and then returns the result.
  • In the example usage section, we define specific values for the length and width variables (5 and 3 respectively).
  • We then call the calculateRectangleArea function with these values to compute the area of the rectangle.
  • Finally, we log the result to the console, providing a clear message indicating what values were used for the length and width, along with the calculated area.
  •  
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript Example</title> <style> .highlight { color: blue; font-weight: bold; } </style> </head> <body> <h2>JavaScript Example</h2> <p id="demo">This is a paragraph.</p> <button onclick="changeText()">Click me</button> <script> function changeText() { var paragraph = document.getElementById("demo"); // Get the paragraph element by its id paragraph.innerHTML = "Text has been changed!"; // Change the content of the paragraph paragraph.className = "highlight"; // Add a CSS class to style the paragraph } </script> </body> </html>

Explanation:

  • This HTML document contains a paragraph element (<p>) with the id "demo" and a button.
  • Inside the <script> tag, there's a JavaScript function changeText() that is triggered when the button is clicked (onclick="changeText()").
  • Inside the changeText() function:
    • It retrieves the paragraph element using document.getElementById("demo").
    • It changes the content of the paragraph using paragraph.innerHTML.
    • It adds a CSS class "highlight" to the paragraph using paragraph.className.
  • The CSS style defined in the <style> section changes the color and weight of the text when the "highlight" class is applied.

 
Previous Post Next Post

Contact Form