Saturday, 30 November 2024

CSS Background Images: A Comprehensive Guide to Enhancing Web Design

The background-image property in CSS is used to set an image as the background of an element. You can reference images from the internet or your local file system. Along with background-image, there are several other properties to consider for better control over how the background image appears on the webpage.

Example 1: Referencing an Image from the Internet

body {
  background-image: url('https://example.com/image.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
}

 

1.   url('https://example.com/image.jpg'): This references the image from a URL on the internet.

2.   background-repeat: no-repeat;: Ensures the image is not repeated.

3.   background-size: cover;: Scales the image to cover the entire element without distorting it. The image might be cropped to fit the element.

4.   background-position: center;: Centers the image within the element.

5.   background-attachment: fixed;: Fixes the image in place so it doesn't move when the user scrolls.

 

Example 2: Referencing an Image from the Local File System

#banner {
  background-image: url('../images/banner.jpg');
  background-repeat: no-repeat;
  background-size: contain;
  background-position: top;
  background-attachment: scroll;
}

 

1.   url('../images/banner.jpg'): This references an image located in the images folder, one level up from the current CSS file's location.

2.   background-repeat: no-repeat;: Prevents the image from repeating.

3.   background-size: contain;: Scales the image to fit within the element without cropping. The entire image is visible but might not cover the whole element.

4.   background-position: top;: Aligns the image to the top of the element.

5.   background-attachment: scroll;: The background image scrolls with the rest of the content.

palace.jpg

 


 

backgroundImage.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Background Image Examples</title>
    <style>
    /* Apply a background image from the internet to the body */
    body {
        background-image: url('../../images/palace.jpg');
        background-repeat: no-repeat;
        background-size: cover;
        background-position: center;
        background-attachment: fixed;
        background-color: #f0f0f0; /* Fallback color */
    }

    h1, p{
        color: darkblue;
        font-size: 30px;
    }
    </style>
</head>
<body>
    <header class="banner">
        <h1>Welcome to My Website</h1>
    </header>
    <section>
        <p>This section demonstrates how to use background images in CSS, both from an internet source and from a local file.</p>
    </section>
</body>
</html>

Adjust the url path accordingly in your html file.

background-image: url('../../images/palace.jpg');

 

Above snippet generate below screen.



 

Previous                                                    Next                                                    Home

Function Parameters and Arguments in JavaScript

Functions can take input values known as parameters. When you call the function, you pass in arguments to those parameters.

 

  • Parameters are the variables defined in a function's signature that specify what kind of inputs the function expects.
  • Arguments are the actual values you pass into the function when calling it.

 

Here’s an example:

 

parameterizedFunctions.js

function greetUser(name) {
    console.log("Hello, " + name + "!!!!!");
}

greetUser("Krishna"); 
greetUser("Hari");

Output

Hello, Krishna!!!!!
Hello, Hari!!!!!

In this example,

1.   name is a parameter.

2.   "Krishna" and "Hari" are arguments passed to the name parameter when calling the function.

Previous                                                    Next                                                    Home

HTML Comments: Enhancing Code Readability and Maintenance

HTML comments are a way to include notes or explanations within your HTML code that won't be displayed in the browser. They help to document your code, making it easier to understand for yourself and others who might work on it in the future.

How to Write HTML Comments

Comments in HTML are enclosed within <!-- and -->.

 

Example

<!-- This is a comment -->
<p>This is a paragraph.</p>
<!-- Comments can be placed anywhere in the HTML document -->

Why Comments are important?

1.   Documentation: Comments can explain what certain parts of the code do, making it easier to understand and maintain, especially in larger projects.

 

2.   Code Organization: They help in organizing the code by separating different sections or components of the HTML file.

 

3.   Temporary Code Removal: Comments can be used to temporarily disable certain parts of the code without deleting them. This is useful for debugging or testing.

 

4.   Collaboration: When working on a project with others, comments can help communicate ideas, instructions, or issues that need attention.

 

Is comments affect rendering of HTML page?

Comments are ignored by the browser and do not affect the rendering of the HTML page. They are visible only in the HTML source code, which can be viewed by right-clicking on the page and selecting "View Page Source" or similar options in different browsers.

 

comments.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Comments Example</title>
</head>
<body>
    <!-- Header Section -->
    <header>
        <h1>My Website</h1>
    </header>

    <!-- Main Content Section -->
    <main>
        <p>Welcome to my website!</p>
    </main>

    <!-- Footer Section -->
    <footer>
        <p>Footer content here.</p>
    </footer>

</body>
</html>

  

Previous                                                    Next                                                    Home

Friday, 29 November 2024

Building a Simple Registration Form in React with State Management

Let’s build a simple registration form using state management in React. This form will capture a user's name, email, and password, and we’ll manage the form inputs with the useState hook.

Step-by-Step Implementation

1.   Create the Form Component: We'll create a RegistrationForm component.

2.   Define State Variables: Use useState to manage the values of the form inputs.

3.   Handle Input Changes: Update the state when the user types in the input fields.

4.   Handle Form Submission: Capture the form data and log it to the console when the form is submitted.

 

 

Follow below step-by-step procedure to build the complete working application.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘user-registration’.

 

Project structure looks like below.

 


Step 2: Create components folder in src folder and define UserRegistration component.

 

UserRegistration.jsx

import { useState } from "react";

export default function UserRegistration() {
  const [myName, setUsername] = useState("");
  const [myEmail, setEmail] = useState("");
  let [disableRegistration, setDisableRegistration] = useState(true);

  function registerUser(event) {
    event.preventDefault();
    console.log(`User ${myName} registered successfully!!!!!`);
  }

  function handleNameChange(event) {
    setUsername(event.target.value);
    handleRegistraiton()
  }

  function handleEmailChange(event) {
    setEmail(event.target.value);
    handleRegistraiton()
  }

  
  function handleRegistraiton(){
    setDisableRegistration(!myName || !myEmail);
  }

  return (
    <form method="POST" onSubmit={registerUser}>
      <label forname="username">Enter Username : </label>
      <input
        type="text"
        id="username"
        value={myName}
        onChange={handleNameChange}
      />
      <br />
      <br />

      <label forname="email">Enter Email : </label>
      <input
        type="text"
        id="email"
        value={myEmail}
        onChange={handleEmailChange}
      />
      <br />
      <br />

      <button disabled={disableRegistration}>Register</button>
    </form>
  );
}

State Initialization

The UserRegistration component uses the useState hook to manage state for user input. Here’s how state is defined.

 

const [myName, setUsername] = useState(""); // State for the username

const [myEmail, setEmail] = useState(""); // State for the email

let [disableRegistration] = useState(true); // State for disabling the registration button

 

·      myName and myEmail: These variables hold the current values of the username and email input fields, respectively.

·      setUsername and setEmail: These functions are used to update the corresponding state variables.

·      disableRegistration: This variable indicates whether the registration button should be disabled based on whether the username and email fields are filled.

 

2. Event Handlers

The component defines two functions that handle changes in the input fields.

function handleNameChange(event) {
  setUsername(event.target.value); // Update the username state with the input value
 handleRegistraiton();
}

function handleEmailChange(event) {
  setEmail(event.target.value); // Update the email state with the input value
 handleRegistraiton();
}

 

·      handleNameChange: This function is called whenever the user types in the username field. It updates the myName state with the current input value.

·      handleEmailChange: Similar to handleNameChange, this function updates the myEmail state when the user types in the email field.

 

3. Disabling Registration Button

The code for managing the disable state of the registration button is.

function handleRegistraiton(){
    setDisableRegistration(!myName || !myEmail);
  }

This snippet checks whether myName or myEmail is empty. If either is empty, disableRegistration is set to true, disabling the button.

 

4. The form submission is handled by the registerUser function.

function registerUser(event) {
  event.preventDefault(); // Prevent default form submission behavior
  console.log(`User ${myName} registered successfully!!!!!`); // Log the username
}

5. Rendering the Form

The component renders a form with input fields for the username and email, along with a register button.

return (
  <form method="POST" onSubmit={registerUser}>
    <label forname="username">Enter Username : </label>
    <input
      type="text"
      id="username"
      value={myName}
      onChange={handleNameChange}
    />
    <br />
    <br />

    <label forname="email">Enter Email : </label>
    <input
      type="text"
      id="email"
      value={myEmail}
      onChange={handleEmailChange}
    />
    <br />
    <br />

    <button disabled={disableRegistration}>Register</button>
  </form>
);

The input fields use the value prop to bind their value to the corresponding state variables (myName and myEmail), ensuring that the UI reflects the current state. The button element has its disabled property set based on the disableRegistration variable.

 

Step 3: Update main.jsx like below.

 

main.jsx

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import UserRegistration from './components/UserRegistration'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <UserRegistration />
  </StrictMode>,
)

Step 4: Build and run the application by executing below commands.

  cd user-registration
  npm install
  npm run dev

Open the url ‘http://localhost:5173/’ in browser, you will see below screen.


 

‘Register’ button is enabled once you enter Some data to Username and Email.

 


Click on Register button, you can see below message in the console.

 

User Krishna registered successfully!!!!!

 

You can download this application from this link.


Previous                                                    Next                                                    Home