The biggest goal of JavaScript is to enable us to perform the operations we want when an event occurs on our page. To ensure this, events that may occur on the page are given a name. We can call a javascript function in the face of the desired event and take the necessary actions.
onClick
Clicking the element is the event.
first method:
<button id="eve">CLICK</button>
<div id="result"></div>
<script>
var Button = document.getElementById("eve");
Button.onclick = function () {
document.getElementById("result").innerHTML = "'onclick' is running successfully."
}
</script>
second method:
<button type="button" onclick="eve();">CLICK</button>
<div id="result"></div>
<script>
function eve() {
document.getElementById("result").innerHTML = "'onclick' is running successfully."
}
</script>
Example:
<h3>Calculate the length of the text.</h3>
<input type="text" id="text" />
<button type="button" onclick="calculate();">calculate</button>
<div id="result"></div>
<div id="mes"></div>
<script>
function calculate() {
var txt = document.getElementById("text").value,
message = document.getElementById("mes").innerHTML = "";
x = txt.length;
try{
if (txt == "") throw "Do not leave empty."
if (!isNaN(txt)) throw "Do not use numbers"
} catch (e) {
mes.innerHTML = e;
}
document.getElementById("result").innerHTML = x;
}
</script>
onDblClick
Double-clicking the element is an event.
<div style="width:100px;
height:100px;
border: solid 1px Black;
text-align:center;
background-color:#ffffff;"
onDblClick="color()"
id="box"></div>
<script>
var variable = 0;
function color() {
var boxColor = document.getElementById("box");
switch (variable) {
case 0: boxColor.style.background = "#e04040";//red
variable++;
break;
case 1: boxColor.style.background = "#40d040";//blue
variable++;
break;
case 2: boxColor.style.background = "#4080f0";//white
variable++;
break;
default: boxColor.style.background = "#ffffff";//white
variable = 0;
break;
}
}
</script>



Leave a comment