Events are the user actions that can be recognized by javascript which includes actions like movement of a mouse, window load, click of a button, submission of a form, etc. Javascript codes are written to perform some action when such an event is detected on the page. Some of the most used events in javascript are listed below.
Events like onFocus(),
Javascript can control event handlings very well. We can define secondary actions when some primary actions are performed by the user.
In this demo, you can see the date displayed when the button is clicked.
<button type="button" class="btn btn-info" onclick="getElementById('demo').innerHTML = Date()">Date & Time</button> <p id="demo"></p>
click - is the event here so whatever instruction we give here to be performed is event handling.
The general syntax is onclick="getElementbyId()" which receives data from the pointed id when the related button is clicked.
In this case, we are pointing to the id named demo that is the p element below the button. So, js will connect to the same p element on click.
Since the p#demo is empty, we have instructed to display the system date inside the p element through .innerHTML = Date() command.
Now, Let's change the innerHTML element of some id where there is already some data.
This is the text seen at first.
<button type="button" class="btn btn-warning" onclick="getElementById('change').innerHTML = 'This is the changed one.'">Change Text</button> <p id="change">This is the text seen at first.</p>
In this example, we placed some text inside the innerHTML in the syntax line and asked the browser to display it inside the the pointed HTML element instead of the data it's been displaying.
Now, Let's add some css to the HTML elements.
Hello Guys, What's up???
<button type="button" class="btn btn-danger" onclick="getElementById('nodisplay').style='display:none'">Hide Me!!</button> <p id="nodisplay">Hello Guys, What's up???</p>
In this example we've added a CSS property of display: none in the element on click of the related button.
<button type="button" class="btn btn-primary" onclick="getElementById('display').style='display:block;color:red'">Show Me!!</button> <p id="display" style="display: none;">Hello Guys, What's up???</p>
In this example we've added CSS property for display and color in the element on click of the related button.
Leave a comment