Javascript DOM Click event via addEventListener()
<!DOCTYPE html> <html lang="en"> <body> <a id="someLink" href="http://java2s.com"> Click Me /*from ww w . ja va 2 s. co m*/ </a> <script> let link = document.getElementById("someLink"); link.addEventListener("click", function (e) { console.log("This link is going nowhere"); e.preventDefault(); }); </script> </body> </html>
Displaying Random Images with Standard Event Handlers
<!DOCTYPE html> <html lang="en"> <body> <img id="img0" src="image1.png" /> <img id="img1" src="image2.png" /> <script> let myImages = [ /* w w w . j av a2s.c om*/ "image1.png", "image3.png", "image4.png", "image2.png" ]; function changeImg(e) { let el = e.target; let newImgNumber = Math.round(Math.random() * 3); while (el.src.indexOf(myImages[newImgNumber]) != -1) { newImgNumber = Math.round(Math.random() * 3); } el.src = myImages[newImgNumber]; } document.getElementById("img0").addEventListener("click", changeImg); document.getElementById("img1").addEventListener("click", changeImg); </script> </body> </html>