JavaScript event handlers are functions that are triggered in response to a specific event happening in the browser, such as a user clicking on a button, moving their mouse over an element, or typing into a form field.
Event handlers are used to execute code in response to these events and can be added to HTML elements using the "on" attribute or added dynamically using JavaScript.
Examples of commonly used event handlers include "onclick" for when a user clicks on an element, "onmouseover" for when a user moves their mouse over an element, and "onsubmit" for when a user submits a form.
<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>
<form>
<input type="button" value="Click on me for Pop-Up"
onclick="alert('I am from Pop-Up');">
<br><br>
<input type="button" value="Click on me for direct text"
onclick="document.write('Directly on Page');">
</form>
</body>
</html>
This code creates a form with two buttons, each with an onclick
attribute that triggers a JavaScript event handler function when the button is clicked.
The first button has an onclick
attribute with the value alert('I am from Pop-Up');
. This means that when the button is clicked, an alert box will pop up on the screen with the message "I am from Pop-Up".
The second button has an onclick
attribute with the value document.write('Directly on Page');
. This means that when the button is clicked, the text "Directly on Page" will be written directly on the page where the button is located, replacing any existing content.
<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>
<script>
function print_stuff() {
document.write("I am from function");
}
</script>
<form>
<input type="button" value="Click to activate Function"
onclick="print_stuff();">
</form>
</body>
</html>
This code creates a function called "print_stuff()" that writes the text "I am from function" to the web page using the document.write() method. It also creates a button in a form that, when clicked, calls the "print_stuff()" function using the onclick attribute.
When the button is clicked, the function is executed and the text "I am from function" is written to the web page.
onclick
is an event handler attribute in HTML and JavaScript that specifies the code to be executed when an element, such as a button, is clicked by the user. The code can be a JavaScript function or a script that is executed when the event occurs.
The onclick
attribute is commonly used to create interactive web pages, such as triggering a pop-up window, showing a message or changing the content of the web page.
No comments:
Post a Comment