Quantcast
Channel: xxxx7 » jQuery
Viewing all articles
Browse latest Browse all 4

BootstrapのTooltipの中身を途中で変更する

$
0
0

Twitter BootstrapTooltipで、中身を変更する方法を書いていきたいと思います。やりたいことは、hover中にtooltipを表示させ、クリックしたらそのtooltip内のテキストを変更する、というものです。

まず、tooltipのベーシックな使い方は次の通りです。htmlはこんな感じ。

<span id="basic" data-toggle="tooltip" title="Tooltip Text">
    ここにカーソルをのせると
</span>

そして、javascriptはこうです。

$(function(){
    $('#basic').tooltip();
});

この要素にカーソルをのせると、titleで指定した文字が浮かび上がります。

image1

さて、hover時とclick時でtitleを変えるには、次のようにします。まずはhtmlから。

<span id="sample">
    ここにカーソルを重ねたりクリックすると
</span>

そして、javascript。

$(function(){

	$('#sample').tooltip({
		trigger: 'manual'
		, animation: false
	});

	$('#sample').hover(function(){
		$(this).attr('title', 'Hover')
			.tooltip('fixTitle')
			.tooltip('show');
	}, function(){
		$(this).tooltip('hide');
	});

	$('#sample').click(function(){
		$(this).attr('title', 'Clicked!')
			.tooltip('fixTitle')
			.tooltip('show');
	});

});

こうすると、hover時、click時で、次のようにtooltipの内容が変わります。

image2

image3

javascriptでどういうことをしているかを簡単に説明します。

まず、最初にオプションの設定をしています。triggerは、どういうタイミングでtooltipを表示させるかを指定するものです。hoverやclickなどを指定できますが、ここでは自分で設定するのでmanualを指定しています。また、animationは切っておきます。

hover時、click時は基本的に同じことをしています。まず、title属性を変更します。そして、それをtooltipの設定に反映するために、fixTitleを実行します。そしてshowすると、tooltipの中身が変更されます。hoverの2つ目の設定は、hoverがoffになったときの処理です。triggerにmanualを指定していたので、自分でhide処理を書きます。


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images