LoginSignup
43

More than 5 years have passed since last update.

# jQueryで特定要素以外クリック時のイベントを取得する

Posted at

よくメニューや、モーダルを作る時に自分以外がクリックされた時に閉じたりするのに使ってるのでメモ。

まずはHTMLとCSSを準備

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>clickMe!</title>
</head>
<body>
  <div class="outer">
    <div class="inner">
      clickMe!
    </div>
  </div>
</body>
</html>

イベント取得

$(document).click(function(event) {
  if(!$(event.target).closest('.inner').length) {
    console.log('外側がクリックされました。');
  } else {
    console.log('内側がクリックされました。');
  }
});

ここから動作確認できます。
https://jsfiddle.net/p4tjgygr/2/

解説

自分以外のクリックイベントを取得するためには全てのクリックをみて確認する必要があります。

$(document).click(function(event) {
// クリックイベントが発生すると毎回ここ通る
});

次にどの要素がクリックされたのかeventとclosestを使って判別します。

$(document).click(function(event) {
  // event.targetをjQueryオブジェクトに変換する
  // closest()を使って自分から先祖要素までinnerクラスがある要素を選択する
  if(!$(event.target).closest('.inner').length) {
    console.log('外側がクリックされました。');
  }
});

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
43