how to use addEventListener in javascript code example
Example 1: javascript onclick event listener
document.getElementById("myBtn").addEventListener("click", function() {
alert("Hello World!");
});
Example 2: js addeventlistener
document.getElementById("example").addEventListener('click', function() {
alert('Click');
});
Example 3: javascript addeventlistener
var element = document.getElementById("#id");
element.addEventListener('click', function(){
console.log("click");
});
Example 4: js addeventlistener
var element=document.getElementById("some_id");
var listener=element.addEventListener('click',function(event){
});
Example 5: javascript pass parameter to event listener
var someEventHander=function(){
console.log(event,param1,param2);
}
document.getElementById("someid").addEventListener('click',someEventHander.bind(event,param1,param2));
Example 6: addEventListener
<body style="height: 5000px">
<script>
function snap(destination) {
if (Math.abs(destination - window.scrollY) < 3) {
scrollTo(window.scrollX, destination);
} else if (Math.abs(destination - window.scrollY) < 200) {
scrollTo(window.scrollX, window.scrollY + ((destination - window.scrollY) / 2));
setTimeout(snap, 20, destination);
}
}
var timeoutId = null;
addEventListener("scroll", function() {
if (timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(snap, 200, parseInt(document.getElementById('snaptarget').style.top));
}, true);
</script>
<div id="snaptarget" class="snaptarget" style="position: relative; top: 200px; width: 100%; height: 200px; background-color: green"></div>
</body>