<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>たねっぱ！ &#187; jQuery</title>
	<atom:link href="https://taneppa.net/tag/jquery/feed/" rel="self" type="application/rss+xml" />
	<link>https://taneppa.net</link>
	<description>コツコツあつめるWeb作りのためのたね　たねっぱ！Web系情報ブログ　Webのお役立ちネタ配信中！</description>
	<lastBuildDate>Tue, 09 May 2023 00:02:06 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>jQueryで要素を絞りこみたい時に使う関数一覧</title>
		<link>https://taneppa.net/jq_filter/</link>
		<comments>https://taneppa.net/jq_filter/#comments</comments>
		<pubDate>Wed, 06 Jul 2016 00:35:38 +0000</pubDate>
		<dc:creator>tanippa!</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">https://taneppa.net/?p=2976</guid>
		<description><![CDATA[既に$(~)で抽出したjQueryの要素の集合を「さらに特定の条件で絞り込みたい！」といった状況が結構あります。今回はそんな時に使用できるjQueryの関数をまとめてみました。]]></description>
				<content:encoded><![CDATA[<p>例えば、以下のようなソースコードがあるとします。</p>
<pre class="brush: xml; title: ; notranslate">
&lt;ul id=&quot;List&quot;&gt;
	&lt;li&gt;1&lt;/li&gt;
	&lt;li class=&quot;red&quot;&gt;2&lt;/li&gt;
	&lt;li&gt;3&lt;/li&gt;
	&lt;li&gt;&lt;span class=&quot;red&quot;&gt;4&lt;/span&gt;&lt;/li&gt;
	&lt;li class=&quot;red&quot;&gt;5&lt;/li&gt;
	&lt;li&gt;6&lt;/li&gt;
&lt;/ul&gt;
&lt;!-- /#List --&gt;
</pre>
<pre class="brush: xml; title: ; notranslate">
$(function() {
  var $list  = $('#List');
  var $items = $list.find('li');
});
</pre>


<p>このように、「$items」にul#List内のli要素が入っているような状況で、「redクラスがついている要素だけ取り出したい」「〜番目の要素を取り出したい」といったような、「もっと要素を条件によって絞り込みたい」って時が結構あります。</p>

<p>今回はそういう場合に使える関数をご紹介したいと思います。</p>

<h2 id="-">順番による絞込</h2>

<h3 id="first-last">first/last</h3>

<p>最初、又は最後の要素を取り出したい場合に使う関数です。</p>

<pre class="brush: xml; title: ; notranslate">
// 最初の要素を取り出す
var $first_item = $items.first();

// 最後の要素を取り出す。
var $last_item = $items.last();
</pre>



<a href="https://taneppa.net/wp-content/uploads/2016/04/first_last.png"><img class="alignnone size-full wp-image-2982" alt="first_last" src="https://taneppa.net/wp-content/uploads/2016/04/first_last.png" width="780" height="550" /></a></pre>
<h3 id="eq-n-">eq(n)</h3>
<p>n番目の要素を取り出したい場合に使う関数です。</p>
<pre class="brush: xml; title: ; notranslate">
// 3番目の要素を取り出す
var $third_item = $items.eq(2);
</pre>

<p>3番目なのに2を指定しているのは間違いではありません。eqの引数は0オリジン（0が最初の要素と対応）なので3番目の要素を取り出したい場合は2を指定する必要があります。</p>
<p><a href="https://taneppa.net/wp-content/uploads/2016/04/eq.png"><img class="alignnone size-full wp-image-2983" alt="eq" src="https://taneppa.net/wp-content/uploads/2016/04/eq.png" width="780" height="550" /></a></p>
<h3 id="slice-start-end-">slice(start, end)</h3>
<p>start番目からend番目までの要素を取り出す場合に使う関数です。</p>

<pre class="brush: xml; title: ; notranslate">
// 3~5番目の要素を取り出す
var $new_items = $items.slice(2, 4);
</pre>

<p>sliceもeqと同様0オリジンなので注意しましょう。</p>
<p><a href="https://taneppa.net/wp-content/uploads/2016/04/slice.png"><img class="alignnone size-full wp-image-2985" alt="slice" src="https://taneppa.net/wp-content/uploads/2016/04/slice.png" width="780" height="550" /></a></p>
<h2 id="css-">CSSセレクタによる絞込</h2>
<h3 id="filter-selector-not-selector-">filter(selector)/not(selector)</h3>
<p>「〜のクラスを持っている（持っていない）要素を取り出す」といったCSSセレクタによる絞込をしたい場合はfilter/not関数を使います。</p>
<pre class="brush: xml; title: ; notranslate">
var $red_items = $items.filter('.red');

var $notred_items = $items.not('.red');
</pre>

<p><a href="https://taneppa.net/wp-content/uploads/2016/04/filter_not.png"><img class="alignnone size-full wp-image-2986" alt="filter_not" src="https://taneppa.net/wp-content/uploads/2016/04/filter_not.png" width="780" height="550" /></a></p>

<p>この関数に関して注意しておきたいのが、「その要素自身がセレクタで指定した条件に適合するかどうか」で抽出されるかどうか判断される点です。（子孫要素が条件を満たそうが関係ないということです）</p>

<p>今回の例で言うと、liタグ自身が「.red」クラスを持っているかどうかで判断されます。なので、4番目のliタグは子要素にspan.redを持っていますが、liタグ自身にはredクラスが付いていないのでfilterではなく、notでの抽出対象となります。</p>


<h2 id="-">子孫要素の有無による絞込</h2>



<h3 id="has-selector-">has(selector)</h3>

<p>filter/notのパターンとは逆に、「子孫要素がセレクタに適合するかどうか」で抽出の判断がされるパターンです。</p>

<pre class="brush: xml; title: ; notranslate">
var $hasred_items = $items.has('.red');
</pre>

<p><a href="https://taneppa.net/wp-content/uploads/2016/04/has.png"><img class="alignnone size-full wp-image-2987" alt="has" src="https://taneppa.net/wp-content/uploads/2016/04/has.png" width="780" height="550" /></a></p>

<p>filter/notの時とは異なり、liタグがredクラスを持っていようが関係なく、子孫要素がredクラスを持っているかどうかで判断されますので4番目のspan.redを子要素として持っているliタグのみが抽出対象となります。</p>

<h2>以上</h2>

<p>「更にこの条件で絞り込みたい」という状況が忘れた頃にやってきて、その度に調べ直すことがよくあるので今回まとめなおしてみました。</p>

<p>以上、たにっぱでした〜</p>
]]></content:encoded>
			<wfw:commentRss>https://taneppa.net/jq_filter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[WordPress]記事投稿時に、タイトルの入力チェックをする方法</title>
		<link>https://taneppa.net/wp_titlechec/</link>
		<comments>https://taneppa.net/wp_titlechec/#comments</comments>
		<pubDate>Mon, 19 Oct 2015 01:34:00 +0000</pubDate>
		<dc:creator>tanippa!</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">https://taneppa.net/?p=2835</guid>
		<description><![CDATA[WordPressでは、記事タイトルの入力チェックをする機能を提供しておりませんので自分で作成する必要があります。なので今回は、タイトルの入力の有無をチェックする方法をご紹介したいと思います。]]></description>
				<content:encoded><![CDATA[<p>AdvancedCustomField(以下ACF)を使っていると、ACFで設定した項目に関しては入力の有無のチェックすることが出来るのですが、残念ながら記事タイトルに関しては入力のチェックをしてくれないので空タイトルの状態でも更新が出来てしまいます。</p>
<p>タイトルは基本的に必須にしたい場合がほとんどだと思いますので、今回はタイトルの入力の有無をチェックする方法をご紹介したいと思います。</p>
<h2 id="-">流れ</h2>
<ul>
  <li>タイトルの入力チェックをするためのJSファイルの作成</li>
  <li>作成したJSファイルを、functions.phpを弄って読み込ませる</li>
</ul>
<h2 id="js-">JSファイルの作成</h2>

<pre class="brush: xml; title: ; notranslate">;(function($){
  var $submitBtn = $('#publish');
  var $titleForm = $('#title');

  $submitBtn.on('click', function(){
    var title = $titleForm.val();

    if (title.length &lt;= 0) {
      alert('タイトルを設定してください。');

      return false;
    }
  });
})(jQuery);</pre>

<p>JSの処理は非常に単純です。</p>
<p>更新ボタンクリック時にタイトルの入力チェックをして、未入力ならアラートを出してキャンセルしています。</p>

<h2 id="functions-php-">functions.phpを弄って読み込ませる</h2>

<pre class="brush: xml; title: ; notranslate">function set_admin_script() {
  print('&lt;script type=&quot;text/javascript&quot; src=&quot;'.get_template_directory_uri().'/common/js/admin.js&quot;&gt;&lt;/script&gt;');
}
add_action('admin_footer', 'set_admin_script');</pre>

<p>「admin_footer」フックを利用することで、管理画面のフッターに任意のコードを出力することが出来ます。</p>
<p>今回は、先ほど作成したJSファイルを読み込ませるようscriptタグを出力させています。</p>
<h2 id="-">以上</h2>
<p>WordPressは管理画面側のカスタマイズが複雑なことが多く、中々上手くいかないこともありますが管理画面が使いにくいとWordPressを導入する意味がなくなってしまいますので頑張って調整しましょう。</p>
<p>以上、たにっぱでした〜</p>]]></content:encoded>
			<wfw:commentRss>https://taneppa.net/wp_titlechec/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ブックマークレットで簡易チェック補助ツールを作ろう！</title>
		<link>https://taneppa.net/bookmarklet/</link>
		<comments>https://taneppa.net/bookmarklet/#comments</comments>
		<pubDate>Thu, 03 Sep 2015 01:47:37 +0000</pubDate>
		<dc:creator>tanippa!</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[効率化]]></category>

		<guid isPermaLink="false">https://taneppa.net/?p=2723</guid>
		<description><![CDATA[ウェブサイト制作をやっていると、チェックするべき項目の多さからチェック漏れしてしまうことがよくありますよね？今回はそんなミスを見つけやすくするために、ブックマークレットを使用してチェックの補助ツールを簡単に作成する方法をご紹介したいと思います。]]></description>
				<content:encoded><![CDATA[<p>ウェブサイト制作をやっていると、チェックするべき項目の多さからチェック漏れしてしまうことがよくありますよね？例えば「aタグの反応する範囲が小さすぎる」なんてミスを自分はよくしてしまいます。</p>
<p>今回はそんなミスを見つけやすくするために、ブックマークレットを使用してチェックの補助ツールを簡単に作成する方法をご紹介したいと思います。</p>
<h2 id="-">ブックマークレット</h2>
<p>ブラウザはブックマークやURLバーから任意のjavascriptを実行することが出来ます。この時に実行するプログラムのことを「ブックマークレット」と言います。</p>
<h3 id="-">簡単な例</h3>
<p>URLバーに</p>

<pre class="brush: xml; title: ; notranslate">javascript:alert('ブックマークレットのテスト');</pre>

<p>と入れてEnterしてみて下さい。アラートが表示されたかと思います。</p>
<p>これが簡単なブックマークレットの例です。</p>
<p>ブックマークレットは</p>

<pre class="brush: xml; title: ; notranslate">javascript:(実行したいjavascriptコード)</pre>

<p>の形式でURLバー、もしくはブックマークから実行することが出来ます。</p>
<h2 id="a-">aタグの反応範囲を視覚的に表示</h2>
<p>それでは、ブックマークレットを利用して冒頭に挙げた「aタグの反応範囲が小さすぎる」というミスを防ぐために、aタグの大きさを視覚的に表示してくれるブックマークレットを作ってみましょう。</p>
<p>javascriptソースは非常に簡単で、以下のとおりです。</p>

<pre class="brush: xml; title: ; notranslate">(function(){
  $('a').css('outline', '1px solid red');
})();</pre>

<p>aタグにoutlineを設定することでaタグの範囲を視覚的に表示させてしまいます。borderと違ってoutlineはレイアウトに影響を与えないので、今回のようなデバッグ目的に最適です。</p>
<p>ブックマークレットは「javascript:」を先頭に付けるだけなので以下の様になります。</p>

<pre class="brush: xml; title: ; notranslate">javascript:(function(){
  $('a').css('outline', '1px solid red');
})();</pre>

<p>これをURLバーに貼り付けてEnterしてみてください。aタグの要素が赤く囲まれるはずです。（GoogleChrome/Macだとペーストする際に「javascript:」の記述が消えてしまったので、その場合は直接入力してください。）</p>
<h3 id="-jquery-">サイトがjQueryを読み込んでいない場合</h3>
<p>先ほどのソースコードはjQueryを使用しているため、このままだとjQueryを読み込んでいないサイトでは動作しません。</p>
<p>そのため、jQueryを読み込むコードを追加しましょう。ソースコードは以下のとおりです。</p>

<pre class="brush: xml; title: ; notranslate">(function(){
  function main() {
    $('a').css('outline', '1px solid red');
  }
  if (typeof jQuery === 'undefined') {
    var scrTmp = document.createElement('script');
    scrTmp.type = 'text/javascript';
    scrTmp.src = '//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js';
    document.body.appendChild(scrTmp);
    scrTmp.onload = main;
  } else {
    main();
  }
})();</pre>

<p>関数mainに実際に実行したい処理を記述し、jQueryがサイトに読み込まれていない場合は、jQueryを読み込んでから実行するようになっています。</p>
<p>このようにしておけばjQueryを読み込んでいないサイトでも使える汎用性の高いブックマークレットが作成できます。</p>
<h2 id="-">以上</h2>
<p>今回はaタグの視覚的な表示のみを例として挙げましたが、発想次第で色々なチェックが可能です。</p>
<p>例えば、</p>
<ul>
<li>モバイルサイトなのに奇数サイズの画像を使用していないか</li>
<li>imgタグのwidth/heightの指定が本来の画像サイズと異なっていないか<br />また、モバイルサイトの場合本来の画像サイズの半分のサイズの指定となっているか</li>
<li>1クリックでW3Cのチェックをする<br />（この場合はサーバーサイドのプログラムも少し必要かと思います）</li>
</ul>
<p>などが挙げられます。</p>
<p>チェック漏れは永遠の課題ではあるのですが、人間の注意力には限界があるので出来る限りツールやシステムに頼って、注意しなくてもミスが見つかるようにしたいですね。</p>
<p>以上、たにっぱでした〜</p>]]></content:encoded>
			<wfw:commentRss>https://taneppa.net/bookmarklet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[jQuery]マウスホバー開閉ナビがアニメーションし続ける問題と解決法</title>
		<link>https://taneppa.net/jq_hover_anim/</link>
		<comments>https://taneppa.net/jq_hover_anim/#comments</comments>
		<pubDate>Wed, 26 Aug 2015 00:25:26 +0000</pubDate>
		<dc:creator>tanippa!</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">https://taneppa.net/?p=2697</guid>
		<description><![CDATA[「マウスホバーで開閉するナビをjQueryで作ったものの、カーソルを連続で往復させるとカーソルを止めてもしばらくナビが開閉し続けてしまう」なんて状況に遭遇したことはないでしょうか？今回はそんな問題の解決法に関して原因とともにご紹介したいと思います。]]></description>
				<content:encoded><![CDATA[<p>「マウスホバーで開閉するナビをjQueryで作ったものの、カーソルを連続で往復させるとカーソルを止めてもしばらくナビが開閉し続けてしまう」なんて状況に遭遇したことはないでしょうか？</p>
<p>ちょうどこの前そんな状況に遭遇したので、今回はこの問題の解決法に関して原因とともにご紹介したいと思います。</p>
<h2 id="-">問題のあるパターン</h2>
<p>「カーソルを乗せると開き、カーソルを外すと閉じるナビ」なんてものを作ろうとした場合、最初に思いつくのは以下のようなコードかと思います。</p>
<h3 id="-">ソースコード</h3>

<pre class="brush: xml; title: ; notranslate">$(function() {
  var $subNav = $('.subNav');
  $('.hoverNav').hover(
    function(){
      $subNav.slideDown();
    },
    function(){
      $subNav.slideUp();
    }
  );
});</pre>

<pre class="brush: xml; title: ; notranslate">&lt;div class=&quot;hoverNav&quot;&gt;
  &lt;p class=&quot;mainNav&quot;&gt;ホバーで開閉&lt;/p&gt;
  &lt;ul class=&quot;subNav&quot;&gt;
    &lt;li class=&quot;box&quot;&gt;ナビ&lt;/li&gt;
    &lt;li class=&quot;box&quot;&gt;ナビ&lt;/li&gt;
    &lt;li class=&quot;box&quot;&gt;ナビ&lt;/li&gt;
    &lt;li class=&quot;box&quot;&gt;ナビ&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;</pre>

<h3 id="-">実例</h3>

<p>次が上記ソースコードの実例なのですが、「ホバーで開閉」ボタンにカーソルを連続で乗せたり外したりしてみて下さい。</p>
<p>すると、カーソルを止めてもしばらく動き続けるかと思います。</p>

<script>
  $(function() {
    var $subNav = $('#Area1 .subNav');
    $('#Area1 .hoverNav').hover(
      function(){
        $subNav.slideDown();
      },
      function(){
        $subNav.slideUp();
      }
    );
  });
</script>
<style>
  #Area1 * {
    margin: 0;
    padding: 0;
  }
  #Area1 .hoverNav {
    width: 200px;
    padding: 5px 0;
    background: #333;
    color: #fff;
    text-align: center;
  }
  #Area1 .subNav {
    display: none;
  }
  #Area1 .subNav li {
    background: none;
  }
</style>
<div id="Area1">
  <div class="hoverNav">
    <p class="mainNav">ホバーで開閉</p>
    <ul class="subNav">
      <li>ナビ</li>
      <li>ナビ</li>
      <li>ナビ</li>
      <li>ナビ</li>
    </ul>
  </div>
</div>


<h2 id="-">原因</h2>
<p>この問題ですが、jQueryは既にアニメーションを実行している時に追加でアニメーションを実行する命令が来た場合、後から来たアニメーションを貯めておいて、今実行しているアニメーションが終わってから実行するという動作をする点が原因となっています。</p>
<p>今回の場合、ボックスを往復する度にアニメーションの実行命令が貯まり、マウスを止めた後も貯まったアニメーションを消化するためにナビが開いたり閉じたりし続けていた、っていう状態ですね。</p>

<h2 id="-">解決法</h2>
<p>以下のようにソースコードを変更すれば解決します。</p>

<h3 id="-">ソースコード</h3>

<pre class="brush: xml; title: ; notranslate">$(function() {
  var $subNav = $('.subNav');
  $('.hoverNav').hover(
    function(){
      // stop関数を追加
      $subNav.stop().slideDown();
    },
    function(){
      // stop関数を追加
      $subNav.stop().slideUp();
    }
  );
});</pre>

<h3 id="-">実例</h3>

<script>
  $(function() {
    var $subNav = $('#Area2 .subNav');
    $('#Area2 .hoverNav').hover(
      function(){
        $subNav.stop().slideDown();
      },
      function(){
        $subNav.stop().slideUp();
      }
    );
  });
</script>
<style>
  #Area2 * {
    padding: 0;
    margin: 0;
  }
  #Area2 .hoverNav {
    width: 200px;
    padding: 5px 0;
    background: #333;
    color: #fff;
    text-align: center;
  }
  #Area2 .subNav {
    display: none;
  }
  #Area2 .subNav li {
    background: none;
  }
</style>
<div id="Area2">
  <div class="hoverNav">
    <p class="mainNav">ホバーで開閉</p>
    <ul class="subNav">
      <li>ナビ</li>
      <li>ナビ</li>
      <li>ナビ</li>
      <li>ナビ</li>
    </ul>
  </div>
</div>

<h3 id="-">解説</h3>
<p>slideDown/slideUp関数の直前にstop関数を追加しただけです。</p>
<p>stop関数は現在実行しているアニメーションを停止させる関数なのですが、これを実行してからslideDown/slideUpなどのアニメーション関数を呼び出すと、現在実行しているアニメーションを破棄して、新しく呼ばれたアニメーションを即実行します。</p>
<h2 id="-">以上</h2>
<p>jQueryアニメーションのこの特徴と解決法は、知っておかないとかなり使い勝手の悪いUIが出来上がってしまうことが多々あるので覚えておきましょう！（自戒）</p>
<p>以上、たにっぱでした〜</p>]]></content:encoded>
			<wfw:commentRss>https://taneppa.net/jq_hover_anim/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>iscroll-probe.jsでiOS7以下でもスクロールイベントを取得</title>
		<link>https://taneppa.net/iscroll-probe/</link>
		<comments>https://taneppa.net/iscroll-probe/#comments</comments>
		<pubDate>Sun, 28 Jun 2015 23:28:57 +0000</pubDate>
		<dc:creator>tanippa!</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">https://taneppa.net/?p=2556</guid>
		<description><![CDATA[iOS8では改善されましたが、iOS7以下でスクロールイベントを取得したいという状況も結構発生するかと思います。そこで今回はiscroll-probe.jsを使用して、スクロールイベントを擬似的に取得する方法をご紹介したいと思います。]]></description>
				<content:encoded><![CDATA[<p>以前はiOSではスクロール中はスクロールイベントが発生せず、スクロール終了時にイベントが発火されるという仕様でしたが、それがiOS8になり改善され、スクロール中にもイベントが発火されるようになりました。</p>
<p>ただ、まだiOS7使用者が無視できない割合で居ることから、案件の対応OSにiOS7が入ることも多く、iOS7以下でスクロールイベントを取得したいという状況も結構発生するかと思います。</p>
<p>そこで、今回はiscroll-probe.jsを使用して、スクロールイベントを擬似的に取得する方法をご紹介したいと思います。</p>
<h2 id="iscroll5-">iScroll5ライブラリの取得</h2>
<p><a href="http://iscrolljs.com/" target="_blank">iScroll 5, smooth scrolling for the web</a></p>
<p>上の公式サイトの「DOWNLOAD」リンクからライブラリ一式をダウンロードしてください。</p>
<p>中に多くのファイルが入っていますが、今回使用するのは「build」ディレクトリ内の「iscroll-probe.js」のみですので、「iscroll-probe.js」を適宜好きな場所へ配置してください。</p>
<h2 id="-">ライブラリの読み込み</h2>
<p>headタグ内で、iscroll-probe.jsを読み込んでください。</p>
<pre class="brush: xml; title: ; notranslate">&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;./common/js/lib/iscroll-probe.js&quot;&gt;&lt;/script&gt;</pre>
<p>今回は一部jQueryを使用するためjQueryも読み込んでいます。使用しない場合は読み込む必要はありません。</p>
<h2 id="html">HTML</h2>
<p>iscrollでは、コンテンツ全体を２つのラッパーで囲む必要があります。</p>
<p>今回は以下の様な構造にします。</p>
<pre class="brush: xml; title: ; notranslate">&lt;body onload=&quot;loaded()&quot;&gt;
  &lt;div id=&quot;WholeWrapper&quot;&gt;
    &lt;div id=&quot;WholeInner&quot;&gt;
      &lt;!-- コンテンツを記述 --&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/body&gt;</pre>
<p>idやクラスには特に規定は無いので自由に付けて大丈夫です。</p>
<p>bodyタグに記述しているonloadコールバック関数に関しては後述します。</p>
<h2 id="css">CSS</h2>
<p>一番外側のラッパーに対しては下記のようなスタイルを当てる必要があります。</p>
<pre class="brush: xml; title: ; notranslate">#WholeWrapper {
  position: absolute;
  z-index: 1;
  top: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  overflow: hidden;
}</pre>
<h2 id="javascript">javascript</h2>
<pre class="brush: xml; title: ; notranslate">&lt;script&gt;
  var myScroll;
  function updatePosition () {
    $(window).trigger('iscroll', {x: this.x, y: this.y});
  }

  // onloadイベント発生時にこの関数を呼び出す
  function loaded () {
    myScroll = new IScroll('#WholeWrapper', {
      deceleration: 0.004, // スクロール時の慣性の強さ
      probeType: 3,
      mouseWheel: true
    });

    myScroll.on('scroll', updatePosition);
    myScroll.on('scrollEnd', updatePosition);
  }

  document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

  $(function(){
    $(window).on('iscroll', function(e, pos){
      console.log(pos); // スクロール中にもスクロール位置が取得可能
    });
  });
&lt;/script&gt;</pre>
<p>IScroll初期化時に指定している「deceleration」は慣性の強さで、この値が大きいほどスクロールがすぐ停止するようになります。初期値は「0.0006」なのですが、この値だとiOS Safariの慣性と比較して慣性が異常に強く、スクロールしすぎてしまうので適宜値を調整しましょう。</p>
<h2 id="-">スクロール系関数</h2>
<p>iScrollには様々な関数が用意されているのですが、その中でも一番使用頻度が多いと思われるスクロール系関数を紹介したいと思います。</p>
<h3 id="scrollto-x-y-time-easing-">scrollTo(x, y, time, easing)</h3>
<p>(x, y)地点へtimeミリ秒かけてスクロールします。</p>
<pre class="brush: xml; title: ; notranslate">myScroll.scrollTo(0, -1000, 500, IScroll.utils.ease.elastic);</pre>
<p>easingはスクロールの際の加減速の仕方のバリエーションで、quadratic,circular,back,bounce,elasticの5パターン存在しています。</p>
<h3 id="scrolltoelement-el-time-offsetx-offsety-easing-">scrollToElement(el, time, offsetX, offsetY, easing)</h3>
<p>要素elまでtimeミリ秒かけてスクロールします。その際、止まる位置はoffsetの指定によってずらすことが可能です。easingはscrollToと同じです。</p>
<pre class="brush: xml; title: ; notranslate">myScroll.scrollToElement(document.getElementById('TargetId'), 1000);</pre>
<p>iScrollは構造上アンカーリンクが効かなくなってしまうので、代わりにこのscrollToElementを使用して機能を実装する必要があります。</p>
<p>他にも、現在のスクロール位置から相対的に移動するscrollByが存在しています。</p>

<h2 id="-">以上</h2>
<p>これで一応iOS7以下でもスクロールイベントを取得出来るようにはなるのですが、前述のとおり、iScrollは内側のラッパーをtranslateにより移動させることにより擬似的にスクロールイベントを再現している仕組みのため、アンカーリンクが正常に機能しません。他にも正常に動作しなくなる、または通常より実装に工数が大幅にかかってしまう機能がある可能性が高いので、使用にはかなり気をつける必要があります。</p>
<p>また、iOS7では動作することを確認しましたが、iOS7未満やAndroidでは動作未確認ですのでご注意ください。</p>
<p>以上、たにっぱでした〜</p>]]></content:encoded>
			<wfw:commentRss>https://taneppa.net/iscroll-probe/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>javascript(jQuery)でメディアクエリを判定する方法(IE9対応)</title>
		<link>https://taneppa.net/mq-judge/</link>
		<comments>https://taneppa.net/mq-judge/#comments</comments>
		<pubDate>Sun, 14 Jun 2015 23:27:16 +0000</pubDate>
		<dc:creator>tanippa!</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">https://taneppa.net/?p=2551</guid>
		<description><![CDATA[レスポンシブサイトを作る際、レイアウト切り替わり時に特定の処理を実行する必要が頻繁に出てくるのですが、単純にjQueryでブラウザ幅を取得して判断する方法ではなかなか上手く行かない場合が多いです。今回は、シンプル・確実に現在の表示レイアウトを判断する方法をご紹介したいと思います。]]></description>
				<content:encoded><![CDATA[<p>レスポンシブウェブデザインなWEBサイトを作る際、レイアウト切り替わり時に特定の処理を実行する必要が頻繁に出てくるのですが、単純にjQueryでブラウザ幅を取得して判断する方法ではなかなか上手く行かない場合が多いです。</p>
<p>そこで今回は、シンプル・確実に現在の表示レイアウトを判断する方法をご紹介したいと思います。</p>
<h2 id="-">現在の表示レイアウトの判断方法</h2>
<p>どのように判断するかというと、スマホ時（もしくはPCレイアウト時）のみに出現する要素を目印として、それが表示されているのかされていないのかを元に判断します。<br />よく目印として使うのはスマホレイアウト時にのみ出るハンバーガーボタン（ナビ開閉のボタン）ですね。</p>
<p>具体例は以下のとおりです。</p>
<pre class="brush: xml; title: ; notranslate">&lt;style&gt;
  #MqMark {
    display: block;
  }
  @media screen and (max-width: 640px) {
    #MqMark {
      display: none;
    }
  }
&lt;/style&gt;
&lt;div id=&quot;MqMark&quot;&gt;&lt;/div&gt;</pre>
<p>上のようなPCレイアウト時のみ出現する要素を目印とします（そのような目印がない場合は作ってしまいましょう）。</p>
<p>javascript部分は以下のようになります。</p>
<pre class="brush: xml; title: ; notranslate">&lt;script&gt;
  $(function() {
    $(window).on('resize', function(){
      if ($('#MqMark').is(':visible')) {
        // PCレイアウト
        console.log('pc');
      } else {
        // スマホレイアウト
        console.log('sp');
      }
    });
  });
&lt;/script&gt;</pre>
<p>この方法だと現在のレイアウトの状態を正確に取得出来るのでオススメです。</p>
<h2 id="-">他の方法</h2>
<p>他の方法として「window.matchMedia」を使用する方法があります。</p>
<pre class="brush: xml; title: ; notranslate">if (window.matchMedia('screen and (max-width:640px)').matches) {
  // スマホレイアウト
  console.log('sp');
} else {
  // PCレイアウト
  console.log('pc');
}</pre>
<h2 id="-">以上</h2>
<p>これからレスポンシブウェブデザインでjavascriptを書くという方や、これまでwidthを使って判定していたという方は是非今回ご紹介した方法を使ってみてください。</p>
<p>以上、たにっぱでした〜</p>]]></content:encoded>
			<wfw:commentRss>https://taneppa.net/mq-judge/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQueryでチェックボックスやラジオボタンの状態を取得する</title>
		<link>https://taneppa.net/jquery-prop/</link>
		<comments>https://taneppa.net/jquery-prop/#comments</comments>
		<pubDate>Mon, 08 Jun 2015 01:19:45 +0000</pubDate>
		<dc:creator>tanippa!</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">https://taneppa.net/?p=2521</guid>
		<description><![CDATA[jQueryでチェックボックスやラジオボタンの状態を取得しようとする時、attr関数では上手く取得することが出来ません。そこで今回はjQueryでのチェックボックスやラジオボタンの状態を取得する方法に関して説明したいと思います。]]></description>
				<content:encoded><![CDATA[<p>jQueryでチェックボックスやラジオボタンの状態を取得しようとする時、最初は</p>
<pre class="brush: xml; title: ; notranslate">$('#TargetID').attr('checked')</pre>

<p>で取得しようとしたのですが、この取得方法には問題がありうまく状態を取得することが出来ませんでした。</p>
<p>そこで、今回はjQueryでのチェックボックスやラジオボタンの状態を取得する方法に関して説明したいと思います。</p>
<h2 id="-">取得方法</h2>
<p>まず、結論として取得する方法を紹介します。</p>
<p>方法は下記の2通りです。</p>
<pre class="brush: xml; title: ; notranslate">$('#TargetID').prop('checked')</pre>
<pre class="brush: xml; title: ; notranslate">$('#TargetID').is(':checked')</pre>
<p>両方共、チェックされていればtrue、チェックされていなければfalseが返却されます。</p>
<p>個人的には後者の方が好みですが、どちらでも問題ありません。</p>
<p>また、checkedだけでなくselectedやdisabledといったプロパティに関しても、attrではなくpropやisを使った方法で取得しましょう。</p>
<h2 id="-">実例</h2>
<p>よくあるパターンとしては、フォームを送信する際、「同意する」チェックボックスにチェックが入っていない状況では送信ボタンが押せないようにするというものを例として挙げたいと思います。</p>
<h3 id="html">HTML</h3>
<pre class="brush: xml; title: ; notranslate">&lt;input id=&quot;AgreeBtn&quot; type=&quot;checkbox&quot;&gt;同意する&lt;br&gt;
&lt;input id=&quot;SubmitBtn&quot; type=&quot;submit&quot; disabled&gt;</pre>

<h3>JavaScript</h3>
<pre class="brush: xml; title: ; notranslate">$('#AgreeBtn').on('change', function(){
  if ($(this).is(':checked')) {
    $('#SubmitBtn').prop('disabled', false);
  } else {
    $('#SubmitBtn').prop('disabled', true);
  }
});</pre>
<h3>動作例</h3>
<script type="text/javascript">// <![CDATA[
$(function() {
    $('#AgreeBtn').on('change', function(){
      if ($(this).prop('checked') == true) {
        $('#SubmitBtn').prop('disabled', false);
      } else {
        $('#SubmitBtn').prop('disabled', true);
      }
    });
  });
// ]]&gt;</script>
<p><input id="AgreeBtn" type="checkbox" />同意する<br /> <input id="SubmitBtn" type="submit" disabled="disabled" /></p>
<h2 id="attr-">attrによる取得の問題点</h2>
<p>これから先は正直知らなくてもあまり問題が無い内容なのですが、何故attrで状態を取得出来ないのか気になり調べてみたのでその内容を書いておきたいと思います。</p>
<pre class="brush: xml; title: ; notranslate">$('#TargetID').attr('checked')</pre>
<p>冒頭でも出したこのコードですが、一見普通に使えそうに見えますが、かなり問題があります。</p>
<p>というのも、checkedの取得にattrを使用した場合、返却値は「checked」か「undefined」になり、さらに対象がチェックされている状態でも状況によってはundefinedが返却されます。つまるところ全く使い物になりません。</p>
<p>これは</p>
<ul>
	<li>attrがDOMの属性を元に値を取得する点</li>
	<li>checkboxにチェックを入れても、DOMの属性は変わらない点</li>
</ul>
<p>この2点が理由です。</p>
<h3 id="attr-dom-">attrがDOMの属性を元に取得する</h3>
<p>DOMの属性っていうのは例えば、</p>
<pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;about.html&quot;&gt;&lt;/a&gt;</pre>
<p>このaタグでいうとhrefが属性で、その値がabout.htmlですね。</p>
<p>では、今回問題になっているcheckboxの場合</p>
<pre class="brush: xml; title: ; notranslate">&lt;input type=&quot;checkbox&quot; checked&gt;</pre>
<p>となるのですが、このHTMLは以下の内容と同じ意味を持ちます。</p>
<pre class="brush: xml; title: ; notranslate">&lt;input type=&quot;checkbox&quot; checked=&quot;checked&quot;&gt;</pre>
<p>つまり、HTMLにcheckedを指定することは「checked属性にcheckedを指定」したのと同じ意味です。なのでattrでcheckedが帰ってくるわけですね。</p>
<p>逆にcheckedの指定がない場合は、そもそもchecked属性自体がDOMに存在していないのでundefinedが返却されることとなります。</p>
<h3 id="checkbox-dom-">checkboxにチェックを入れてもDOMの属性は変わらない</h3>
<p><a href="https://taneppa.net/wp-content/uploads/2015/05/スクリーンショット-2015-05-14-13.55.301.png"><img class="alignnone size-full wp-image-2531" alt="スクリーンショット 2015-05-14 13.55.30" src="https://taneppa.net/wp-content/uploads/2015/05/スクリーンショット-2015-05-14-13.55.301.png" width="320" height="320" /></a></p>
<p>この画像はチェックボックスにチェックを入れた時のDOMの状態を開発ツールで表示したものなのですが、見てわかる通りチェックボックスにチェックが入っているのにcheckboxのDOMにはchecked属性が追加されていません。</p>
<p>attrはDOMの属性を引っ張ってくるので、今回のパターンのようにDOMの状態が変わらないものに関してはattrでは状態を取得しようが無いということです。</p>
<h2 id="-">以上</h2>
<p>propやisなんて関数は自分も最初は存在自体を知らなかったのですが、今回のように無いと困ることもあるのでぜひ覚えておきましょう。</p>
<p>以上、たにっぱでした〜</p>
]]></content:encoded>
			<wfw:commentRss>https://taneppa.net/jquery-prop/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQueryでのサイズ、座標の取得方法まとめ</title>
		<link>https://taneppa.net/jquery-size/</link>
		<comments>https://taneppa.net/jquery-size/#comments</comments>
		<pubDate>Sun, 31 May 2015 23:30:35 +0000</pubDate>
		<dc:creator>tanippa!</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">https://taneppa.net/?p=2479</guid>
		<description><![CDATA[jQueryを使っていると、頻繁に要素のサイズや位置を取得する機会があります。サイズや座標を取得する関数は複数あって「どれがどこのサイズ、座標を取得するの？」ってごっちゃになりがちなので、今回はサイズ、位置関係のそれぞれのjQuery関数の違いなどをまとめて紹介したいと思います。]]></description>
				<content:encoded><![CDATA[<p>jQueryを使っていると、頻繁に要素のサイズや位置を取得する機会があります。</p>
<p>サイズや座標を取得する関数は複数あって「どれがどこのサイズ、座標を取得するの？」ってごっちゃになりがちなので、今回はサイズ、位置関係のそれぞれのjQuery関数の違いなどをまとめて紹介したいと思います。</p>
<h2 id="-">目次</h2>
<ul>
<li><a class="scroll" href="#TargetAnchor1">サイズ取得関係の関数</a><ul>
<li><a class="scroll" href="#TargetAnchor1-1">サイズ取得の基本</a></li>
<li><a class="scroll" href="#TargetAnchor1-2">ページ全体のサイズやブラウザサイズを取得したい</a></li>
</ul>
</li>
<li><a class="scroll" href="#TargetAnchor2">要素の座標の取得方法</a><ul>
<li><a class="scroll" href="#TargetAnchor2-1">座標取得の基本</a></li>
<li><a class="scroll" href="#TargetAnchor2-2">番外編：offsetParentってoffsetと関係あるの？</a></li>
</ul>
</li>
<li><a class="scroll" href="#TargetAnchor3">スクロールした距離を取得する方法</a></li>
</ul>
<div id="TargetAnchor1"></div>

<h2 id="-">サイズ取得関係の関数</h2>
<div id="TargetAnchor1-1"></div>

<h3 id="-">サイズ取得の基本</h3>
<p>サイズの取得には、以下の4つの方法があります。</p>
<table>
<thead>
<tr>
<th style="text-align:left">方法</th>
<th style="text-align:left">説明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">width()<br />height()</td>
<td style="text-align:left">paddingを除いた内側のサイズを取得</td>
</tr>
<tr>
<td style="text-align:left">innerWidth()<br />innerHeight()</td>
<td style="text-align:left">paddingを含んだサイズを取得</td>
</tr>
<tr>
<td style="text-align:left">outerWidth()<br />outerHeight()</td>
<td style="text-align:left">paddingとborderを含んだサイズを取得</td>
</tr>
<tr>
<td style="text-align:left">outerWidth(true)<br />outerHeight(true)</td>
<td style="text-align:left">marginまで含んだサイズを取得</td>
</tr>
</tbody>
</table>
<p>各方法を画像でわかりやすくするとこんな感じです。</p>

<p><a href="https://taneppa.net/wp-content/uploads/2015/04/size1.png"><img src="https://taneppa.net/wp-content/uploads/2015/04/size1.png" alt="size1" width="769" height="528" class="alignnone size-full wp-image-2488" /></a></p>

<p>ここで注意しないといけないのは、width()はcssで設定したwidthとは違うという点です。</p>
<p>どういうことか、実例を示します。</p>

<pre class="brush: xml; title: ; notranslate">&lt;style&gt;
  #Size1Box {
    width: 100px;
    height: 100px;
    padding: 20px;
    margin: 10px;
    border: 5px solid black;
    background: red;
    box-sizing: border-box;
  }
&lt;/style&gt;</pre>

<p>このようにborder-boxを指定した要素を用意します。この要素の各サイズを出力すると下記のようになります。</p>

<script>
  $(function() {
    $box = $('#Size1Box');

    $('#Size1Output').html(outputSize($box));

    function outputSize($target) {
      var output = '';
      output += 'width: ' + $target.width() + '<br />';
      output += 'innerWidth: ' + $target.innerWidth() + '<br />';
      output += 'outerWidth(): ' + $target.outerWidth() + '<br />';
      output += 'outerWidth(true): ' + $target.outerWidth(true);

      return output;
    }
  });
</script>

<style>
  #Size1Box {
    width: 100px;
    height: 100px;
    padding: 20px;
    margin: 10px;
    border: 5px solid black;
    background: red;
    box-sizing: border-box;
  }
</style>

<div id="Size1Box"></div>
<p id="Size1Output"></p>

<p>このように、スタイルでは「width: 100px」と指定したのに、width()の出力値が50となっているはずです。<br />これは、「box-sizing: border-box;」により「中身の幅 + padding + border = cssのwidth」となり、jQueryのwidth関数は「中身の幅」を返すためcssのwidthからpaddingとborder分差し引いた50pxが返されるという事です。</p>

<p>jQueryのwidth関数は「中身の幅」を取得するための関数ということに注意しましょう。<br />cssで設定されたwidthの値を取得したい場合は、</p>

<pre class="brush: xml; title: ; notranslate">$('#IdName').css('width');</pre>

というようにcss関数で取得しましょう。

<div id="TargetAnchor1-2"></div>

<h3 id="-">ページ全体のサイズやブラウザサイズを取得したい</h3>
<p>document,windowを使用すれば可能です。</p>
<p>ページ全体のサイズは</p>

<pre class="brush: xml; title: ; notranslate">$(document).width();
$(document).height();</pre>

<p>ブラウザサイズは</p>

<pre class="brush: xml; title: ; notranslate">$(window).width();
$(window).height();</pre>

<p>で取得出来ます。（document,windowに対するinnerWidthやouterWidthは、widthと同じ値を返します。）</p>
<div id="TargetAnchor2"></div>

<h2 id="-">要素の座標の取得方法</h2>
<div id="TargetAnchor2-1"></div>

<h3 id="-">座標取得の基本</h3>
<table>
<thead>
<tr>
<th style="text-align:left">方法</th>
<th style="text-align:left">説明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">offset()</td>
<td style="text-align:left">ページ左上に対する座標を取得</td>
</tr>
<tr>
<td style="text-align:left">position()</td>
<td style="text-align:left">cssのpositionの基準となる親から見た座標を取得</td>
</tr>
</tbody>
</table>
<p>cssのpositionはまだよくわからない、という方は、<a href="/position/">CSS positionを使ってみよう！</a>や、<a href="/position_property/">見ながら覚えよう！positionプロパティ「absolute」と「relative」についてのお話</a>を参考に読んでみてください。</p>

<p><a href="https://taneppa.net/wp-content/uploads/2015/04/offset.png"><img src="https://taneppa.net/wp-content/uploads/2015/04/offset-448x500.png" alt="offset" width="448" height="500" class="alignnone size-medium wp-image-2487" /></a></p>

<p>offset()とposition()は、</p>

<pre class="brush: xml; title: ; notranslate">{
  top: xxx,
  left: xxx
}</pre>

<p>という形の連想配列を返すので、topかleftのどちらかだけ必要、という場合は</p>

<pre class="brush: xml; title: ; notranslate">var topOffset =  $('#IdName').offset().top;
var leftOffset = $('#IdName').offset().left;</pre>

<p>というような書き方で片方だけを取得出来ます。</p>
<div id="TargetAnchor2-2"></div>

<h3 id="-offsetparent-offset-">番外編：offsetParentってoffsetと関係あるの？</h3>
<p>答え：ないです。</p>
<p>offsetParentは、positionが設定されている先祖要素の中で一番近い物を取得する関数です。</p>
<p>名前からoffsetと関係がありそうに見えてしまいますが、どちらかというと関係あるのはpositionですね。</p>
<div id="TargetAnchor3"></div>

<h2 id="-">スクロールした距離を取得する方法</h2>
<p>どれだけページをスクロールしたかは「scrollTop」関数を使用します</p>

<pre class="brush: xml; title: ; notranslate">var vScrollDistance = $(window).scrollTop();</pre>

<p>また、横方向にどれだけスクロールしたかも「scrollLeft」関数で取得出来ます。</p>

<pre class="brush: xml; title: ; notranslate">var hScrollDistance = $(window).scrollLeft();</pre>

<p>それぞれは下記のようなイメージです。</p>

<p><a href="https://taneppa.net/wp-content/uploads/2015/04/scroll.png"><img src="https://taneppa.net/wp-content/uploads/2015/04/scroll-448x500.png" alt="scroll" width="448" height="500" class="alignnone size-medium wp-image-2486" /></a></p>

<h2 id="-">以上</h2>
<p>以上がjQueryでのサイズ、座標取得方法のまとめでした。</p>
<p>サイズの取得なんかはwidthとinnerWidthがごっちゃになりがちなので注意しておきましょう。</p>
<p>以上、たにっぱでした〜。</p>]]></content:encoded>
			<wfw:commentRss>https://taneppa.net/jquery-size/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[jQuery]イベントのバブリングって何？</title>
		<link>https://taneppa.net/jquery-bubbling/</link>
		<comments>https://taneppa.net/jquery-bubbling/#comments</comments>
		<pubDate>Mon, 25 May 2015 23:56:20 +0000</pubDate>
		<dc:creator>tanippa!</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">https://taneppa.net/?p=2460</guid>
		<description><![CDATA[javascriptにはイベントのバブリングという概念があります。この概念を知らないと、理解不能な状況に陥る事があるので、今回はバブリングを紹介したいと思います。]]></description>
				<content:encoded><![CDATA[<p>javascriptにはイベントのバブリングという概念があります。</p>

<p>この概念を知らないと、理解不能な状況に陥る事があるので、今回はバブリングを紹介したいと思います。</p>

<h2>バブリングとは？</h2>

<p>バブリングとは、「ある要素でイベントが発生した際に、親や祖先要素にも同じイベントが発生する事」です。</p>

<a href="https://taneppa.net/wp-content/uploads/2015/04/bubbling1.png"><img src="https://taneppa.net/wp-content/uploads/2015/04/bubbling1-493x500.png" alt="bubbling1" width="493" height="500" class="alignnone size-medium wp-image-2462" /></a>

<p>上の画像のように、子要素をクリックしてclickイベントが発生すると、その親要素、祖先要素でもclickイベントが発生します。</p>

<h3>具体例</h3>

<p>以下の例では、表示されている3つのボックスが親子関係で、それぞれにclickイベントを設定し、クリックするとアラートを出すようにしています。</p>

<style>
  .rectBox {
    width : 50%;
    height: 50%;
  }
  .rectBox.root {
    width : 200px;
    height: 200px;
  }
  .rectBox.black {
    background-color: #2c3e50;
  }
  .rectBox.red {
    background-color: #c0392b;
  }
  .rectBox.blue {
    background-color: #3498db;
  }
</style>

<script>
  $(function() {
    var $ancestor = $('#AncestorBox');
    var $parent   = $('#ParentBox');
    var $child    = $('#ChildBox');

    $ancestor.on('click', function(e) {
      alert('I am ancestor');
    });

    $parent.on('click', function(e) {
      alert('I am parent');
    });

    $child.on('click', function(e) {
      alert('I am child');
    });

  });
</script>

<div id="AncestorBox" class="rectBox root black">
  <div id="ParentBox" class="rectBox red">
    <div id="ChildBox" class="rectBox blue"></div>
  </div>
</div>

<p>ここで、ChildBox(青色のボックス)をクリックすると、ChildBoxのアラートだけでなく、ParentBoxやAncestorBoxのアラートも発生するはずです、これがイベントのバブリングの実例です。</p>

<pre class="brush: xml; title: ; notranslate">&lt;style&gt;
  .rectBox {
    width : 50%;
    height: 50%;
  }
  .rectBox.root {
    width : 200px;
    height: 200px;
  }
  .rectBox.black {
    background-color: #2c3e50;
  }
  .rectBox.red {
    background-color: #c0392b;
  }
  .rectBox.blue {
    background-color: #3498db;
  }
&lt;/style&gt;

&lt;script&gt;
  $(function() {
    var $ancestor = $('#AncestorBox');
    var $parent   = $('#ParentBox');
    var $child    = $('#ChildBox');

    $ancestor.on('click', function(e) {
      alert('I am ancestor');
    });

    $parent.on('click', function(e) {
      alert('I am parent');
    });

    $child.on('click', function(e) {
      alert('I am child');
    });

  });
&lt;/script&gt;

&lt;div id=&quot;AncestorBox&quot; class=&quot;rectBox root black&quot;&gt;
  &lt;div id=&quot;ParentBox&quot; class=&quot;rectBox red&quot;&gt;
    &lt;div id=&quot;ChildBox&quot; class=&quot;rectBox blue&quot;&gt;&lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>

<h3>stopPropagationによるバブリングのストップ</h3>

<p>この親にもイベントが発生していくバブリングの仕組みが都合が良い場合もあるのですが、問題がある場合も度々発生します。</p>

<p>その場合は、stopPropagationによりバブリングをストップさせることが可能です。</p>

<a href="https://taneppa.net/wp-content/uploads/2015/04/bubbling2.png"><img src="https://taneppa.net/wp-content/uploads/2015/04/bubbling2-493x500.png" alt="bubbling2" width="493" height="500" class="alignnone size-medium wp-image-2463" /></a>

<p>先ほどのバブリングの例を、stopPropagationを使用してバブリングしないようにした例は以下の通りです。</p>

<script>
  $(function() {
    var $ancestor = $('#AncestorBox2');
    var $parent   = $('#ParentBox2');
    var $child    = $('#ChildBox2');

    $ancestor.on('click', function(e) {
      alert('I am ancestor');
e.stopPropagation();
    });

    $parent.on('click', function(e) {
      alert('I am parent');
e.stopPropagation();
    });

    $child.on('click', function(e) {
      alert('I am child');
e.stopPropagation();
    });

  });
</script>

<div id="AncestorBox2" class="rectBox root black">
  <div id="ParentBox2" class="rectBox red">
    <div id="ChildBox2" class="rectBox blue"></div>
  </div>
</div>

<pre class="brush: xml; title: ; notranslate">&lt;script&gt;
  $(function() {
    var $ancestor = $('#AncestorBox');
    var $parent   = $('#ParentBox');
    var $child    = $('#ChildBox');

    $ancestor.on('click', function(e) {
      alert('I am ancestor');
      e.stopPropagation(); // 追加
    });

    $parent.on('click', function(e) {
      alert('I am parent');
      e.stopPropagation(); // 追加
    });

    $child.on('click', function(e) {
      alert('I am child');
      e.stopPropagation(); // 追加
    });

  });
&lt;/script&gt;</pre>

<p>今回のパターンだと、ChildBoxをクリックした場合でもアラートは１回しか発生しなかったはずです。</p>

<p>また、stopPropagation以外に「return false」でもバブリングをストップすることが可能です。</p>

<p>「return false」にはバブリングのストップ以外に、要素本来のイベントの動作（aタグの場合clickイベントに反応してリンク先に飛ぶ、等）をしないようにする効果もあるので、状況に応じて使い分けましょう。</p>

<h2>mouseover/mouseoutとmouseenter/mouseleaveの違い</h2>

<p>要素上にマウスが乗った・離れた際に発生するmouseover/mouseout及びmouseenter/mouseleaveイベントの違いの一つはイベントのバブリングが発生するか否かです。</p>

<p>mouseover/mouseoutイベントではバブリングが発生しますが、mouseenter/mouseleaveイベントはバブリングが発生しません。</p>

<h3>具体例</h3>

<p>実際に問題が発生する具体例として、「赤い領域にマウスが乗ったら、領域が一回点滅するような演出」を実装する必要が出てきたとします。</p>

<p>何も考えずにmouseoverを使用した場合、下記のような実装をしてしまうと思います。</p>

<script>
  $(function() {
    $('#MouseWrapper .parentBox').on('mouseover', function(e) {
      $(this).animate({
        opacity: '0.5'
      }, 'fast').animate({
        opacity: '1'
      }, 'fast');
    });
  });
</script>

<style>
  #MouseWrapper .parentBox {
    width: 100px;
    height: 100px;
    padding: 50px;
    background-color: #c0392b;
  }
  #MouseWrapper .childBox {
    width: 100px;
    height: 100px;
    background-color: #2c3e50;
  }
</style>

<div id="MouseWrapper">
  <div class="parentBox">
    <div class="childBox"></div>
  </div>
</div>

<pre class="brush: xml; title: ; notranslate">&lt;script&gt;
  $(function() {
    $('#MouseWrapper .parentBox').on('mouseover', function(e) {
      $(this).animate({
        opacity: '0.5'
      }, 'fast').animate({
        opacity: '1'
      }, 'fast');
    });
  });
&lt;/script&gt;

&lt;style&gt;
  #MouseWrapper .parentBox {
    width: 100px;
    height: 100px;
    padding: 50px;
    background-color: #c0392b;
  }
  #MouseWrapper .childBox {
    width: 100px;
    height: 100px;
    background-color: #2c3e50;
  }
&lt;/style&gt;

&lt;div id=&quot;MouseWrapper&quot;&gt;
  &lt;div class=&quot;parentBox&quot;&gt;
    &lt;div class=&quot;childBox&quot;&gt;&lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>

<p>この場合、赤い領域にマウスを乗せたときにちゃんと点滅しますが、何故か黒い領域にマウスが乗った時も点滅してしまいます。</p>

<p>この原因は、mouseover/mouseoutがバブリングを発生させるため、黒い領域に対してmouseoverイベントが発生した際に、親要素である赤い領域にもmouseoverイベントが発生してしまうためです。</p>

<p>他にも、mouseover/mouseoutイベントは子要素から親要素にマウスが移動した際にもmouseoverイベントが発生してしまうため、その時にも点滅してしまいます。</p>

<p>mouseover/mouseoutのようなマウスホバーイベントに関してバブリングが発生してほしい状況もあるかもしれませんが、どちらかというとバブリングしてしまうことによって問題が発生してしまう事が多いためmouseenter/mouseleaveを基本的には使用した方が良いと思います。</p>

<h2>以上</h2>

<p>バブリングは結構ややこしい概念なのですが、理解しておかないと原因がわからない挙動が発生したりして解決に時間がかかってしまうことがありそうなので、出来るだけ早く理解しておいた方がいいかと思いました。</p>]]></content:encoded>
			<wfw:commentRss>https://taneppa.net/jquery-bubbling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>【JQueryライブラリ】簡単に高さを揃えられるjquery.tile.jsを使ってみよう。</title>
		<link>https://taneppa.net/tilejs/</link>
		<comments>https://taneppa.net/tilejs/#comments</comments>
		<pubDate>Thu, 30 Apr 2015 02:12:31 +0000</pubDate>
		<dc:creator>yanoppa!</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[初心者向け]]></category>

		<guid isPermaLink="false">https://taneppa.net/?p=2508</guid>
		<description><![CDATA[【JQueryライブラリ】簡単に高さを揃えられるjquery.tile.jsを使ってみよう。 こんばんちわ、や [...]]]></description>
				<content:encoded><![CDATA[<div style="line-height:2;">
<h2>【JQueryライブラリ】簡単に高さを揃えられる<span class="fB">jquery.tile.js</span>を使ってみよう。</h2>
<p>こんばんちわ、やのっぱです(´・ω・｀)v</p>
<p>今回は良く利用するJQueryライブラリ、tile.jsの使い方をお話していきます。<br />
それではやっていきましょう。</p>
<h3>まずは設置から</h3>
<p>まずはダウンロードし、設置をしていきます。</p>
<p>配布元の<a href="http://urin.github.io/jquery.tile.js/" target="_blank">jquery.tile.js Demos</a>から【Download compressed】(compressedはmin化、uncompressedは展開された状態です)を右クリックで保存、またはクリックして出てきたソースを保存またはコピペしてjquery.tile.jsの名前で保存し任意のフォルダに格納します。</p>
<p>次に、jQueryとjquery.tile.jsをhead内に<span class="fB">読み込み</span>、使用出来るようにします。</p>
<pre class="brush: xml; title: ; notranslate">
&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;格納場所のパスをいれます/jquery.tile.js&quot;&gt;&lt;/script&gt;
</pre>
<p>これでとりあえず読み込まれ使用出来る状態です。</p>
<p>このようなHTMLを用意してみました。<br />
画像とテキストの入ったliですね。<br />
これにtileを適応すると、一番高さがあるものに揃います。</p>
<pre class="brush: xml; title: ; notranslate">
&lt;ul class=&quot;testList clearfix&quot;&gt;
	&lt;li class=&quot;testBox&quot;&gt;
		&lt;p class=&quot;img&quot;&gt;&lt;img src=&quot;http://placehold.jp/150x150.png&quot;&gt;&lt;/p&gt;
		&lt;p class=&quot;text&quot;&gt;テキストテキストテキストテキストテキスト&lt;/p&gt;
	&lt;/li&gt;
	&lt;li class=&quot;testBox&quot;&gt;
		&lt;p class=&quot;img&quot;&gt;&lt;img src=&quot;http://placehold.jp/150x150.png&quot;&gt;&lt;/p&gt;
		&lt;p class=&quot;text&quot;&gt;テキストテキストテキストテキストテキストテキストテキストテキスト&lt;/p&gt;
	&lt;/li&gt;
	&lt;li class=&quot;testBox&quot;&gt;
		&lt;p class=&quot;img&quot;&gt;&lt;img src=&quot;http://placehold.jp/150x150.png&quot;&gt;&lt;/p&gt;
		&lt;p class=&quot;text&quot;&gt;テキストテキストテキストテキスト&lt;/p&gt;
	&lt;/li&gt;
	&lt;li class=&quot;testBox&quot;&gt;
		&lt;p class=&quot;img&quot;&gt;&lt;img src=&quot;http://placehold.jp/150x150.png&quot;&gt;&lt;/p&gt;
		&lt;p class=&quot;text&quot;&gt;テキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト&lt;/p&gt;
	&lt;/li&gt;
	&lt;li class=&quot;testBox&quot;&gt;
		&lt;p class=&quot;img&quot;&gt;&lt;img src=&quot;http://placehold.jp/150x150.png&quot;&gt;&lt;/p&gt;
		&lt;p class=&quot;text&quot;&gt;テキストテキストテキストテキストテキストテキストテキスト&lt;/p&gt;
	&lt;/li&gt;
	&lt;li class=&quot;testBox&quot;&gt;
		&lt;p class=&quot;img&quot;&gt;&lt;img src=&quot;http://placehold.jp/150x150.png&quot;&gt;&lt;/p&gt;
		&lt;p class=&quot;text&quot;&gt;テキストテキストテキストテキストテキスト&lt;/p&gt;
	&lt;/li&gt;
	&lt;li class=&quot;testBox&quot;&gt;
		&lt;p class=&quot;img&quot;&gt;&lt;img src=&quot;http://placehold.jp/150x150.png&quot;&gt;&lt;/p&gt;
		&lt;p class=&quot;text&quot;&gt;テキストテキストテキスト&lt;/p&gt;
	&lt;/li&gt;
	&lt;li class=&quot;testBox&quot;&gt;
		&lt;p class=&quot;img&quot;&gt;&lt;img src=&quot;http://placehold.jp/150x150.png&quot;&gt;&lt;/p&gt;
		&lt;p class=&quot;text&quot;&gt;テキストテキストテキストテキストテキストテキストテキストテキストテキスト&lt;/p&gt;
	&lt;/li&gt;
&lt;/ul&gt;
</pre>
<h3>指定class全てに適用</h3>
<p>使用方法は至って簡単です。<br />
head内にこちらを記述します</p>
<pre class="brush: xml; title: ; notranslate">
&lt;script type=&quot;application/javascript&quot;&gt;
  $(function(){
    $(&quot;.testBox&quot;).tile();
  });
&lt;/script&gt;
</pre>
<p>これで、class .testBoxがついている要素全てが一番高い要素の高さになります。<br />
しかし、これだと具合がわるいこともしばしばです。<br />
なので、グループ分けをすることもできます。</p>
<h3>個数を指定して適用</h3>
<pre class="brush: xml; title: ; notranslate">
&lt;script type=&quot;application/javascript&quot;&gt;
  $(function(){
    $(&quot;.testBox&quot;).tile(4);  
  });
&lt;/script&gt;
</pre>
<p>このように.tile();の()の中に数字をいれることで数字の数ごとで揃わせることができます。<br />
4であるならば、.testBox4つずつ揃うようになります。</p>
<p>テキストのみの場合はこれでOKです。<br />
上記のHTMLのように画像が入っているとなると、多少付け足しが必要になってきます。<br />
画像が入っていると、画像を読み込む前にtile.jsが実行されてしまうからです。<br />
付け足したのがこちらです</p>
<h3>画像を含む場合の記述</h3>
<pre class="brush: xml; title: ; notranslate">
&lt;script type=&quot;application/javascript&quot;&gt;
  $(window).load(function(){
    $(&quot;.testBox&quot;).tile(4);
  });
&lt;/script&gt;
</pre>
<p>$(function～のところを$(window).load(function～とつけたすことで、画像を読み込んでから実行となります。<br />
これで、画像を含んだ場合でも崩れることはなくなります。<br />
簡単な記述で実装でき、とても便利なのでぜひ使用してみてください。それではっ</p>
</div>]]></content:encoded>
			<wfw:commentRss>https://taneppa.net/tilejs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
