0% found this document useful (0 votes)
5 views

Events (CSS) 3rd Year

Uploaded by

smrutigadave
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Events (CSS) 3rd Year

Uploaded by

smrutigadave
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Introduction to Key Events and

Button Event Handling in


JavaScript
What are Events in JavaScript?
Examples of Events:

Events are actions recognized by the browser, usually triggered by user interactions or browser
activities.

User-triggered: clicks, key presses, mouse movements

Browser-triggered: loading, resizing, error detection

Purpose: Events allow developers to create interactive web applications.


Key Events in JavaScript
Key events are associated with the keyboard actions of a user

Types of Key Events:

keydown: Triggered when a key is pressed down.

When it Occurs: Fires as soon as the key is pressed.

keyup: Triggered when a key is released.

When it Occurs: Fires when the key is released after pressing

keypress: Triggered when a key is pressed and held (works for character keys).

When it Occurs: Fires while the key is pressed down (deprecated for non-character keys)

Properties Available: Similar to keydown, but primarily used for capturing character input.

Use Cases: Capturing user input, keyboard shortcuts, game controls


Key Events Handling
// Add an event listener for the 'keyup' event
<html>
document.addEventListener("keyup", function() {
<body>
// Display a message when a key is released
<div id="panel">Press a key...</div>
panel.innerHTML += "<br/>Key Released";
<script>
});
// Get the panel element where the event details will be displayed
// Add an event listener for the 'keypress' event
var panel = document.getElementById("panel");
document.addEventListener("keypress", function(e) {

// Display the character corresponding to the key pressed

// Add an event listener for the 'keydown' event


panel.innerHTML += "<br/>Character: " + String.fromCharCode(e.keyCode);

document.addEventListener("keydown", function() {
});

// Display a message when a key is pressed </script>

panel.innerHTML += "<br/>Key Pressed"; </body>

}); </html>
Button Events in JavaScript
Definition: Button events are triggered when users interact with buttons on the webpage.

Common Button Events:

click: Fires when a button is clicked.

dblclick: Fires when a button is double-clicked.

mouseover/mouseout: Fires when the mouse enters or leaves the button area.

Use Cases: Handling form submissions, triggering actions, user confirmation.


Button Event Handling
<html> // Add an event listener for the 'click' event

<body> button.addEventListener("click", function(event) {

<button id="myBtn">Click for a // Show an alert message with event details


message!</button> alert("Hello World!\n\nEvent type: " +
event.type + "\nEvent target: " +
<script>
event.target.nodeName);
// Get the button element by its ID
});
var button =
</script>
document.getElementById("myBtn");
</body>

</html>
Practical Uses of Event Handling

Form Validation: Checking input values when users submit a form.

Interactive Elements: Enabling actions like dropdown menus, sliders, and tabs.

Gaming: Handling character movement using key events.

Animations: Triggering animations based on user actions.


Changing Attribute Values Dynamically in JavaScript
Definition:

In JavaScript, you can change HTML element attributes dynamically using


scripting. This allows for creating interactive web pages where attributes like
value, style, class, or even data attributes can be altered based on user actions.
Changing Attribute Values Based on User Selection
<html>
<body>
<head>

<title>HTML Form</title> <p>Select a mobile phone from the following list:</p>

<script type="text/javascript">

// Function to handle the selection change in the dropdown <!-- Dropdown list with an 'onchange' event handler -->

function onSelectionChange(element) { <select onchange="onSelectionChange(this)">

// Get the selected value from the dropdown <option value="iPhone">iPhone</option>

var selected = <option value="Samsung Galaxy">Samsung


element.options[element.selectedIndex].value; Galaxy</option>

<option value="OnePlus">OnePlus</option>
// Display an alert showing the selected item
<option value="Google Pixel">Google Pixel</option>
alert("You have selected " + selected);
<option value="Xiaomi">Xiaomi</option>
}
</select>
</script>
</body>
</head>
Practical Use Cases:
Form Handling: Change the form's appearance or submit different data based on
the user's selections.

Dynamic Content Loading: Load specific content or settings when a user selects
an option.

Styling Changes: Adjust styles or themes dynamically based on user


preferences.
Changing Option Lists Dynamically
1. Enhanced User Experience 2. Real-Time Feedback and Adaptation

Dynamically changing option lists help create Dynamically changing lists can be used to give
interactive and responsive forms. When the real-time feedback or adapt the options
options in a dropdown list change based on user available based on other form fields. For
input (such as selecting a radio button or instance, in a booking form, the list of available
checkbox), it makes the interface feel more time slots can change based on the selected
tailored and user-friendly. date, giving users a more accurate and current
view

For example, if a user selects "Fruits" from a list,


showing a dropdown of relevant fruit options
immediately is more intuitive than showing
unrelated items like vegetables.
Code // Check the value to determine whether to display
fruits or vegetables

if (elementValue == 1) {
<html>
// Add options for fruits
<head>

<title>HTML Form</title> optionList.add(new Option("Mango", 1));

<script type="text/javascript"> optionList.add(new Option("Banana", 2));

// Function to update the dropdown list based on the } else if (elementValue == 2) {


selected radio button
// Add options for vegetables
function updateList(elementValue) {
optionList.add(new Option("Potato", 1));
var optionList = document.getElementById("optionList");
optionList.add(new Option("Cabbage", 2));

// Clear the current options }

optionList.innerHTML = ""; }

</script>
<!-- Radio buttons to choose between Fruits and
<body>
Vegetables -->
<form name="myform" action="" <input type="radio" name="group" value="1"
method="post"> checked="true" onclick="updateList(this.value)">Fruits

<p> <input type="radio" name="group" value="2"


onclick="updateList(this.value)">Vegetables
<select id="optionList" name="OptionList"
size="2"> <br>

<option value="1">Mango</option>
<input name="Reset" value="Reset" type="reset">
<option value="2">Banana</option>
</p>
</select>
</form>
<br>
</body>

</html>
Evaluating checkbox selections
1. Collect User Preferences: Allows users to choose multiple options, like favorite items or
preferences.

2. Flexible Input Handling: Users can select any combination of options.

3. Conditional Actions: Enables performing specific actions based on the user's selections.

4. Form Validation: Helps ensure required selections are made (e.g., "Choose at least two
options").
<html>

<head> // Display the selected values

<title>HTML Form</title> document.write(x);

<script type="text/javascript"> }

// Function to evaluate selected checkboxes </script>

function selection() { </head>

var x = "You selected: "; <body>

<form name="myform" action="" method="post">

// Access the form's checkboxes <p>Select your favorite fruits:<br>

with (document.forms.myform) {
<!-- Checkbox inputs for different fruits -->
// Check if each checkbox is selected, then add its value to
<input type="checkbox" name="a" value="Apple">Apple
'x'
<input type="checkbox" name="b" value="Banana">Banana
if (a.checked == true) x += a.value + " ";

if (b.checked == true) x += b.value + " "; <input type="checkbox" name="o" value="Orange">Orange

if (o.checked == true) x += o.value + " "; <input type="checkbox" name="p" value="Pear">Pear

if (p.checked == true) x += p.value + " "; <input type="checkbox" name="g" value="Grapes">Grapes

if (g.checked == true) x += g.value + " "; </p>

}
<!-- Button to trigger the selection function -->

<input type="button" value="Show"


onclick="selection()">

</form>

</body>

</html>
Changing labels dynamically
Dynamic Label Changes: It allows updating labels or button text on the fly based
on user actions. This makes the user interface more interactive and responsive.

Improves User Experience: Users can see relevant options or instructions based
on their selections without needing to reload the page.
if (elementValue === "Cars") {

<html> toggleButton.value = "Show Bikes";

<head> optionList[0].text = "Sedan";

optionList[0].value = "Sedan";
<title>HTML Form</title>
optionList[1].text = "SUV";
<script type="text/javascript">
optionList[1].value = "SUV";
// Function to update the list based on
selected value } else if (elementValue === "Bikes") {

toggleButton.value = "Show Cars";


function updateList(elementValue) {
optionList[0].text = "Mountain Bike";
var toggleButton =
document.getElementById("toggleButton"); optionList[0].value = "Mountain Bike";

optionList[1].text = "Road Bike";


var optionList =
document.forms.myform.OptionList; optionList[1].value = "Road Bike";

}
</head>

<body>

<form name="myform" action="" method="post">

<p>

<select name="OptionList" size="2">

<option value="Sedan">Sedan</option>

<option value="SUV">SUV</option>

</select>

<br>

<input id="toggleButton" value="Show Bikes" type="button"


onclick="updateList(this.value)">

</p>

</form>

</body>

</html>
Manipulating form elements
Dynamic Interaction: Allows users to interact with forms in real-time, providing instant feedback based on their
input.

Validation: Ensures that user inputs meet specific criteria before submission, enhancing data integrity.

Automatic Field Updates: Enables automatic generation of values in one field based on inputs from another
field

(e.g., generating an email address from the first and last names).

User Experience: Improves user engagement by making forms more intuitive and user-friendly.

Form Customization: Allows developers to tailor forms based on user choices, making them more relevant to
the task at hand.
<html> </head>

<head> <body>
<title>HTML Form</title> <form name="myform" action="" method="post">
<script type="text/javascript"> <p>
function addLocation() {
City: <input type="text" name="City"/><br>
with (document.forms.myform) {
Country: <input type="text"
if (City.value.length > 0 && Country.value.length name="Country"/><br>
> 0) {
Location: <input type="hidden"
// Concatenate city and country to create a name="Location"/><br>
location string
<input name="Submit" value="Submit"
Location.value = City.value + ", " + type="button" onclick="addLocation()"/>
Country.value;
</p>
}
</form>
}
</body>
}
</html>
Intrinsic JavaScript Functions
Definition: Intrinsic JavaScript functions are built-in methods provided by the
JavaScript language that allow developers to manipulate web elements and
manage events without the need for additional libraries or frameworks.

Usage in Forms: They can be used to handle form submissions, reset forms, and
validate user input seamlessly.
Examples:

document.forms: Accesses form elements by their name, enabling interaction


with form data.

.submit(): Submits the form programmatically.

.reset(): Resets the form fields to their default values.


<html>

<head>

<title>HTML Form</title>

</head>

<body>

<form name="myform" action="" method="post">

<p>

Email: <input type="text" name="Email"/><br>

Phone Number: <input type="text" name="Phone"/><br>

<img src="submit.jpg"
onclick="javascript:document.forms.myform.submit()" alt="Submit"/>

<img src="reset.jpg"
onclick="javascript:document.forms.myform.reset()" alt="Reset"/>

</p>

</form>

</body>
Disabling Elements

Definition: Disabling elements in HTML refers to preventing user interaction with form elements (like
input fields, buttons, etc.) by setting their state to "disabled." This is often used to indicate that certain
actions cannot be performed until specific conditions are met.

Usage:

Form Control: Disabled form elements do not submit their values with the form, making them useful for
controlling user input.

User Experience: Disabling inputs can help guide users by preventing them from interacting with
elements that should not be available at a particular time.
<html>

<head>

<script type="text/javascript">

function ToggleDisabled() {

var text = document.getElementById("myText");

// Toggle the disabled property

if ('disabled' in text) {

text.disabled = !text.disabled; // Enable if disabled, disable if


enabled

</script>

</head>

<body>

<input type="text" id="myText" disabled value="Disabled value" />

<button onclick="ToggleDisabled();">Change State</button>

</body>
Read-Only Elements
Definition: Read-only elements in HTML allow users to view content without the ability to modify
it. This is useful for displaying information that should not be changed by the user while still
allowing them to interact with the element (e.g., copying the content).

Usage:

Text Areas: Read-only text areas are commonly used to display pre-filled or calculated data that
the user should not alter.

User Interface: Using read-only elements enhances the user experience by clearly indicating
that certain data is informational and cannot be changed.
<html>

<head>

<script type="text/javascript">

function changeState() {

var textarea = document.getElementById("myText");

textarea.readOnly = !textarea.readOnly; // Toggle the


read-only state

</script>

</head>

<body>

<textarea id="myText" rows="3"


readonly="readonly">Change this text</textarea>

<button onclick="changeState();">Change me</button>

</body>

</html>

You might also like