DOM event

jQuery版
監聽事件一覽

連結事件與動作:addEventListener()

點擊觸發:”click”

method 1

button#btn try to click
//1 select the id
var btn = document.querySelector("#btn");
//2 event function
//event listener function(callback function)
//only the event happens, we call this function
//if we want to call it when webpage loads, we use
//clicked();
//()→means callling the function
//if we dont't have ()→just mention it
var clicked = function() {
  btn.textContent = "you clicked me!!"
};

//3 combine 1 and 2
//addEvenetListener(event, function)
//clicked()→×, clicked→○
//"clicked" means mouse click
btn.addEventListener("click", clicked);

method 2 : anonymous function

var btn = document.querySelector("#btn");


btn.addEventListener("click",
  //anonymous function
  function(){
    btn.textContent="you clicked me!!";
});
Display

滑鼠滑過互動:”mousemove”, clientX, clientY

div#box
  img#face(src="https://goo.gl/EZspJs" width=300)
.beard
  width: 5px
  height: 5px
  background-color: #000
  border-radius: 100%
  position: absolute
//"mousemove"
//clientX
//clientY

//select the id
var face=document.querySelector("#face");

//draw beard
var draw=function(evt){
  var beard=document.createElement("div");
  beard.className="beard";
  document.querySelector("#box").appendChild(beard);
  beard.style.top=evt.clientY+"px";
  beard.style.left=evt.clientX+"px";
};

//combine
face.addEventListener("mousemove",draw);

Display

value:儲存表單資料

label What's your name
  input#name
br
label What's languague you speak
  select#lang
    option(value="en") English
    option(value="jp") Japanese
    option(value="ch") Chinese
br
button#btn click me
#message
//select elements
var btn=document.querySelector("#btn");
//event listener function
var clickBtn=function(){
  //add user's name
  //value: to find what user typed
  //to store the name value when btn clicked
  var name=document.querySelector("#name").value;
  //store the lang
  var lang=document.querySelector("#lang").value;
  var greeting
  if(lang==="en"){
    greeting="hallo "+name;
  }else if(lang==="jp"){
    greeting="こんにちは "+name;
  }else {
    greeting="你好 "+name;
  }
  //var greeting="Heyaz "+name;
  document.querySelector("#message").textContent=greeting
};
//combine
btn.addEventListener("click",clickBtn);
Display



preventDefault():取消預設屬性

.bgm
  a#music(href="https://www.kasandbox.org/programming-sounds/rpg/giant-no.mp3") START MUSIC
//progressive enhancement

//select
var music=document.querySelector("#music");

var musicClick = function(e){
  //cancel default behavior
  //preventDefault(): let it not turn to the new mp3 url
  e.preventDefault();
  //create audio tag
  var audio=document.createElement("audio");
  audio.src="https://www.kasandbox.org/programming-sounds/rpg/giant-no.mp3";
  audio.autoplay="true";
  document.querySelector("#bgm").appendChild(audio);
};

//combine
music.addEventListener("click",musicClick);

Display

Leave a Reply

Your email address will not be published. Required fields are marked *