このエントリーをはてなブックマークに追加

知っておくと得をするjQueryのスニペット12個

知っておくと得をするjQueryのスニペット12個

基本業務で使っているjQueryのスニペットです。HTMLとCSSも必要なものもありますが、簡単に実装できます。こうゆうスニペットをたくさんもっていると作業が効率よくできていいですよね。特に、新規のサービスの時なんかは以前使ったコードを使いまわします。そのほうが不具合がないので!!

アコーディオン

簡単に実装できるアコーディオンメニューです。FAQとかで質問をクリックしたら答えがニュルっとでてくるアレです。

JS

$('.js-accordion-btn').on('click', function(event){
    event.preventDefault();
    var $this = $(this);

     $this.next().slideToggle(300);
});

HTML

<dl class="p-accordion">
	<dt class="p-accordion__item p-accordion__item--タイトル js-accordion-btn">タイトル</dt>
	<dd class="p-accordion__item p-accordion__item--text">
		テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、
		テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、
		テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト、テキスト
	</dd>
</dl>

css

.p-accordion{
	margin: 0 -16px;
}
.p-accordion__item{
	position: relative;
	margin-bottom: 0;
	padding: 16px 32px 16px 48px;
	font-weight: normal;
	font-size: 14px;
}

.p-accordion__item--title:before{
	background: #5c6dd4;
}
.p-accordion__item--text{
	display: none;
	background: #440770;
}
.p-accordion__item--text:before{
	background: #9525d6;
}

tab

タブメニューですね。これもよく使います。ちなみに、cssはflex-box使ってます。タブメニューは均等割り付けになるようになってます。

JS

$('.js-tab-btn').on('click', function(event){
    event.preventDefault();
    var $this = $(this);

    $this.parent().siblings().removeClass('is-active').end().addClass('is-active');

    var tabId = $this.data('tabid');
    $this.closest('.js-tab').find('.js-tab-body').each(function(){
        var $content = $(this);
        if($content.data('contentid') == tabId){
            $content.removeClass('is-hidden');
        }else{
            $content.addClass('is-hidden');
        }
    });
});

HTML

<div class="c-tab js-tab">
	<ul class="c-tab__menu">
		<li class="c-tab__menu__item is-active"><a href="#" class="c-tab-btn u-br-l-0 js-tab-btn" data-tabid="1">tab1</a></li>
		<li class="c-tab__menu__item"><a href="#" class="c-tab-btn js-tab-btn" data-tabid="2">tab2</a></li>
	</ul>
	<div class="c-tab__body js-tab-body" data-contentid="1">
		コンテンツ1
	</div>
	<div class="c-tab__body js-tab-body is-hidden" data-contentid="2">
		コンテンツ2
	</div>
</div>

CSS

.c-tab{
	display: block;
	width: 100%;
}
.c-tab__menu{
	display: -webkit-box;
	display:         box;
	margin-bottom: 24px;
	margin-bottom: 16px;
	width: 100%;
	list-style: none;
	text-align: center;
}
.c-tab__menu__item{
	width: 100%;

	-webkit-box-flex: 1;
	        box-flex: 1;
}
.c-tab__body{
	margin-bottom: 24px;
	width: 100%;
}

.c-tab__body.is-hidden{
	display: none;
}

ページ内スクロール

スクロールトップにも、ページ内リンクにも対応してます。結構使える。

JS

$('.js-scroll-link').click(function(){ 
    var speed = 200; //移動完了までの時間(sec)を指定
    var $href= $(this).attr("href"); 
    var $target = $($href == "#" || $href == "" ? 'html' : $href);
    var $position = $target.offset().top - 100;

    $("html, body").animate({scrollTop:$position}, speed, "swing");
    return false;
});

空の要素を削除

以下のコードの場合は空のpタグです。用途に応じてセレクタを変えてください。

JS

$(function () {
    $('p').filter(function () {
        var text_empty = $.trim($(this).text()) === '';
        return text_empty;
    }).remove();
});

jQueryでロールオーバー

JS

jQuery(function(){
	jQuery('a img').hover(function(){
		jQuery(this).attr('src', jQuery(this).attr('src').replace('_off', '_on'));
	}, function(){
		if (!jQuery(this).hasClass('currentPage')) {
			jQuery(this).attr('src', jQuery(this).attr('src').replace('_on', '_off'));
		}
	});
});

幅とか高さ取得系

UIではないけど、覚えておくといろいろと便利。

JS

$(window).width(); // 表示領域幅
$(window).height(); // 表示領域高
$(document).width(); // ドキュメント幅
$(document).height(); // ドキュメント高

スクロールの方向で表示されたり隠れたりするヘッダー

スマホサイト作る時によく使います。

JS

jQuery(document).ready(function($){
	var slideHeader = new SlideHeader($('.js-header-bar'));
});

function SlideHeader(el){
    this.initialize(el);
    this.onScroll();
}

SlideHeader.prototype.initialize = function(el){
    this.$el = el;
    this.$window = $(window);

    this.start_pos = 0;

}

SlideHeader.prototype.onScroll = function(){
    var self = this;

    var _touch = ('ontouchstart' in document) ? 'touchmove' : 'scroll';
    this.$window.on(_touch, function(){
        var $current_pos = $(window).scrollTop();

        if($current_pos > 0){
            if ($current_pos > self.start_pos) {
                self.slideOut();
            }else{
                self.slideIn();
            }
        }else{
            self.slideIn();
        }
        self.start_pos = $current_pos;
    });
}

SlideHeader.prototype.slideIn = function(){
    this.$el.removeClass('is-slideout');
}

SlideHeader.prototype.slideOut = function(){
    this.$el.addClass('is-slideout');
}

HTML

<header role="banner" class="l-header js-header-bar">
	ヘッダー
</header>

CSS

.l-header{
	position: fixed;
	top: 0;
	left: 0;
	z-index: 700;
	background: #00a1b0;
	-webkit-transition: -webkit-transform .3s;
	transition-property: box-shadow, transform;
}

.l-header.is-slideout{
	-webkit-transition: -webkit-transform .3s;
	-webkit-transform: translate3d(0, -60px, 0);
}

inputが空白の場合はsubmitさせない

Form内のinputが入力されていない場合は、Enterやsubmitボタンを押してもsubmitさせたくない時に。

JS

$('.js-searchform').submit(function(){
	var $input = $(this).find('.js-search-input');
	if($input.val().length == 0){
		return false;
	}
});

リンク切れの画像を置換する

no-imageの画像出したりですかね。

JS

$('img').on('error', function () {
  $(this).prop('src', 'img/broken.png');
});

アドレスバー隠す

スマホのアドレスバーを隠すJavaScriptです。

JS

window.addEventListener("load", function() {
    setTimeout(scrollBy, 100, 0, 1);
}, false);

現在のページのURL取得

JS

	alert(location.href);

現在ページURLのパス名を取得

	alert(location.pathname);

イチマルニデザインブログをフォローしよう

イチマルニデザインブログではTwitterアカウントでWebに関する情報をつぶやいています。フォローすることで最新情報をすぐに受け取ることができます

今すぐフォローしよう!

いいなと思ったらシェアお願いします

このエントリーをはてなブックマークに追加

同じカテゴリーの記事

ページの先頭へ