イベントを設定する(1)

イベント

何かが起こったとき、予約したコードを実行する

  • click(クリックされたとき)
  • mouseenter(マウスがのったとき)
  • mouseleave(マウスがおりたとき)
  • hover(mouseenterとmouseleaveを一度に)
  • focus(フォーカスが当たったとき)
  • blur(フォーカスが外れたとき)

click

jQueryObject.click(イベントハンドラ);


《index.html》

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>jQuery 〜</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="jquery-1.9.1.min.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<div id="div1">div!</div>
</body>
</html>


《style.css

#div1{
	background:pink;
	padding:20px;
	cursor: pointer;
}


《script.js》

$(function(){
	$('#div1').click(function(){
		$('#div1').text('クリックされました');
	});
});


mouseenter/mouseleave

jQueryObject.mouseenter(イベントハンドラ);
jQueryObject.mouseleave(イベントハンドラ);


《index.html》

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>jQuery 〜</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="jquery-1.9.1.min.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<div id="div1">div!</div>
</body>
</html>


《style.css

#div1{
	background:pink;
	padding:20px;
	cursor: pointer;
}


《script.js》

$(function(){
	$('#div1').mouseenter(function(){
		$('#div1').text('マウスのりました');
	});
	$('#div1').mouseleave(function(){
		$('#div1').text('マウスおりました');
	});
});

mouseover/mouseout


リンクの中にアイコンがある場合でも、アイコンではなくリンク全体に反応してしまいます。
アイコンからマウスがはなれたことを感知できません。

hover

jQueryObject.hover(mouseenterイベントハンドラ, mouseleave(イベントハンドラ);


《index.html》

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>jQuery 〜</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="jquery-1.9.1.min.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<div id="div1">div!</div>
</body>
</html>


《style.css

#div1{
	background:pink;
	padding:20px;
	cursor: pointer;
}


《script.js》

$(function(){
	$('#div1').hover(function(){
		$('#div1').text('マウスのりました');
	}, function(){
		$('#div1').text('マウスおりました');
	});
});
  • mouseenterとmouseleaveを同時に使う場合がほとんどです。そのときには「hover」で短く記述します

focus/blur

  • focusはinput要素やtextareaにフォーカスが当たったとき
  • blurはフォーカスが外れたとき
jQueryObject.focus(イベントハンドラ);
jQueryObject.blur(イベントハンドラ);


《index.html》

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>jQuery 〜</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="jquery-1.9.1.min.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<input type="text" id="input1">
</body>
</html>


《style.css

.active{
	background-color:#F8F3D0;
}


《script.js》

$(function(){
	$('#input1').focus(function(){
		$('#input1').addClass('active');
	});
	$('#input1').blur(function(){
		$('#input1').removeClass('active');
	});
});