こんにちは!セミマサです。
私のサイトでも使用しているWordPressテーマ「Cocoon」では記事のタイトルとURLをコピーするボタンが用意されています。
このボタンがどのように動いているのか気になったので、実際にそれっぽいボタンを作成してみました!
デモサイト
下のボタンを押すと今回作成したデモサイトへ移動します。
事前準備
今回はjQueryだけでなく、Font Awesome5とclipboard.min.jsを使用します。
HTML
<div id="modal-main"><p class="modal-text">タイトルとURLをコピーしました</p></div>
<section>
<div class="box">
<h1 class="heading">コピーボタンデモ</h1>
<div class="copy" data-clipboard-text=""><i class="fas fa-paste"></i>コピー</div>
</div>
</section>
今回のHTMLです。
・コピー内容となるdata-clipboard-textはjQueryで取得したものを格納するので空欄となっています。
CSS
@charset "UTF-8";
html, body, div,h1,p,section {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent; }
body {
line-height: 1; }
section {
display: block; }
.box{
padding: 20vh 5vw;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center}
.heading{
font-size: 3rem;
margin-bottom: 50vh;}
.fas{
padding-right: 1vw;}
.copy {
background-color: #333;
cursor: pointer;
padding: 12px 0;
text-align: center;
color: white;
border-radius: 5px;
width: 50%;
font-size: 1.2rem;
transition: all .5s;}
.copy:hover{
opacity: .7;}
#modal-main {
display: none;
width: 50%;
height: 25%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
border-radius: 8px;
background-color: rgba(0, 0, 0, 0.3);
color: white;
position: fixed;
z-index: 2; }
.modal-text {
position: fixed;
top: 50%;
left: 50%;
width: 100%;
padding: 0 2%;
transform: translate(-50%, -50%); }
@media screen and (max-width: 480px) {
#modal-main {
width: 80%;}
.heading{
font-size: 2rem;}
}
今回のCSSになります。
jQuery
<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.13/clipboard.min.js"></script>
<script>
$(function(){
//clipboard.min.jsが動作する要素をクラス名で指定
var clipboard = new Clipboard('.copy');
$('.copy').click(function(){
//モーダルウィンドウを表示し、1.5秒後に閉じる
$("#modal-main").fadeIn("slow").delay(1500).fadeOut("slow");
});
});
$(window).on('load', function() {
//URLを取得
var url = location.href;
//タイトルを取得
var title = document.title;
//タイトルとURLを連結
var copy_contents = title + " " + url;
$('.copy').attr('data-clipboard-text', copy_contents);
});
</script>
今回のjQueryです。
・ウィンドウのロード時にURLとタイトルを取得・連結し、コピーボタンのdata-clipboard-textに渡しています。
・クリック時の処理は、メソッドチェーンを利用してモーダルウィンドウを表示する処理と1.5秒後に閉じる処理を連結しています。
おわりに
それっぽい動きのボタンが作れて満足しました。