An event is an action that happens in the system that can be collected in javascript to be used as desired.
For example, when a button is pressed within a web page, an event occurs that can be responded to in any way.
There are different types of events in Javascript:
To add an event to a web page we will use "addEventListener", and inside it the type of event to use:
<script type="text/javascript">
document.addEventListener("keydown", function(event){
console.log(event);
});
</script>
To further analyze this event we can inspect it from the console of our web browser.
In the following example we are going to add a new event given by means of a button in which the background color of the web page is changed:
<button id="changeBackground">Change Background</button>
<script type="text/javascript">
var button = document.getElementById("changeBackground");
function randomNumber(number){
return Math.round(Math.random()*number);
}
document.addEventListener("click", function(event){
var selectedColour = [
randomNumber(255),
randomNumber(255),
randomNumber(255)
];
document.body.style.backgroundColor = "rgb("+selectedColour[0]+", "+selectedColour[1]+", "+selectedColour[2]+")"
});
</script>
In the following example we are going to create our own event and then use it:
<script type="text/javascript">
//I create my personal event
var myEvent = new CustomEvent("exampleEvent", { "detail" : "hello user" });
//I launch my event
document.dispatchEvent(myEvent);
document.addEventListener("exampleEvent", function(event){
console.log(event.detail);
});
</script>
In the following example we show an event generated simply by hovering over it, we can use the example of changing the background color when pressing the button, simply with this change:
<button id="changeBackground">Change Background</button>
<script type="text/javascript">
var button = document.getElementById("changeBackground");
function randomNumber(number){
return Math.round(Math.random()*number);
}
document.addEventListener("mousemove", function(event){
var selectedColour = [
randomNumber(255),
randomNumber(255),
randomNumber(255)
];
document.body.style.backgroundColor = "rgb("+selectedColour[0]+", "+selectedColour[1]+", "+selectedColour[2]+")"
});
</script>
Tips on SEO and Online Business
Next Articles
Previous Articles