ラベル JavaScript の投稿を表示しています。 すべての投稿を表示
ラベル JavaScript の投稿を表示しています。 すべての投稿を表示

2013年5月11日土曜日

JavaScriptでポップアップウィンドウを表示する最小サンプル

ポップアップウィンドウを最も簡単に実現できるのは、JavaScriptのalert関数である。

alertのサンプル

しかしながら、alert関数では表示するテキストをパラメータとして渡せるだけなので、ポップアップウィンドウとは言い難い。

次に簡単に実現できるのは、window.openを利用する方法である。

window.openのサンプル

用途によってはこれでも十分なのだが、要はブラウザの新規ウィンドウを開いているだけなので、ウィンドウの細かい制御はできないし、セキュリティの設定によってはポップアップウィンドウの警告が表示されてしまう場合もある。

現実的な方法としては、jQueryとCSSを使う方法になる。

まず、ページ内に、下記のようにポップウィンドウとして表示するDIVタグを用意しておく。
<div id="popupwindow">
  <div id="popuowindow_message"></div>
  <div id="popupwidow_close">OK</div>
</div>
このままでは、DIVタグの中身が丸見えなので、スタイルシートで下記のように非表示にしておく。
#popupwindow {
  display: none;
}
JavaScript側では、下記のように記述する。
$("#popupwindow3").click(function(e){
  $('#popuowindow_message').text('こんにちは!');
  $('#popupwindow').css({top: 400, left: 20}).fadeIn(100);
  $('#popupwidow_close').click(function() {$('#popupwindow').fadeOut(100);});
  return false;
});
1. メッセージのテキストを設定。
2. ポップアップウィンドウの表示。
3. OKがクリックされた場合にウィンドウを非表示。

popup windowで表示するサンプル

最小サンプルなので、余計な装飾などは行っていないが、DIVタグをCSSで装飾して見栄えを良くしたり、JavaScriptのイベントを追加してタイトルバーでドラッグできるようにするなど、いろいろなことはできるようだ。

今回作成したソースコードの参照はこちらから。

https://gist.github.com/torafugu/5559183

今回参考にさせていただいたブログ記事。

jQueryで「window.open」タイプのポップアップウィンドウ方法
http://black-flag.net/jquery/20100630-1210.html

ドラッグ可能なポップアップウインドウを作ろう - jQuery入門
http://ponk.jp/jquery/basic/ipop

2012年11月19日月曜日

画面オープン直後にProcessing.jsのスクリプトを実行するサンプル

jQueryで画面のオープン直後に処理を実行する場合は、$(document).ready を利用することが一般的なようだが、このイベントに合わせてProcessingのスクリプトを実行しようとしてもうまくいかない。

具体的には、下記のようなソースコードでは、
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="jquery.js"></script>
<script src="processing-1.4.1.js" type="text/javascript"></script>
<script type="text/processing" data-processing-target="mycanvas">
void setup()
{
  size(200, 200);
  colorMode(RGB, 100);
  noLoop();
}

void draw()
{
  fill(90);
  ellipse(70, 70, 100, 100);
}

void addEllipse()
{
  fill(60);
  ellipse(90, 90, 70, 70);
}
</script>
<script type="text/javascript">
$(document).ready(function(){
  var p= Processing.getInstanceById("mycanvas");
  p.addEllipse();
})
</script>
</head>
<body>
  <p>
  <canvas id="mycanvas"></canvas>
  </p>
  </body>
</html>
次のようなエラーメッセ―ジが表示されてしまう。


$(document).ready イベントでは、画面上のオブジェクトの読み込みがすべて完了した時点ではなく、画面上のDOM(Document Object Model)の読み込みが完了した時点、つまり、HTMLのソースコードの読み込みが完了した時点となる。

このタイミングでは、Processingの画面描画が完了していないので、Processingの関数を呼ぼうとしても、エラーになってしまうようだ。

$(document).ready の代わりに、$(window).load を使ったらうまくいった。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="jquery.js"></script>
<script src="processing-1.4.1.js" type="text/javascript"></script>
<script type="text/processing" data-processing-target="mycanvas">
void setup()
{
  size(200, 200);
  colorMode(RGB, 100);
  noLoop();
}

void draw()
{
  fill(90);
  ellipse(70, 70, 100, 100);
}

void addEllipse()
{
  fill(60);
  ellipse(90, 90, 70, 70);
}
</script>
<script type="text/javascript">
$(window).load(function(){
  var p= Processing.getInstanceById("mycanvas");
  p.addEllipse();
})
</script>
</head>
<body>
  <p>
  <canvas id="mycanvas"></canvas>
  </p>
  </body>
</html>

2012年9月16日日曜日

Ruby on RailsのRJSを利用したXMLHttpRequestの最小サンプル:その2

XMLHttpRequestを使えるようにRailsが作成したファイルを変更してみる。

▽tests_controller.rb の変更

変更前
  # GET /tests/1
  # GET /tests/1.json
  def show
    @test = Test.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @test }
    end
  end
変更後
  # GET /tests/1
  # GET /tests/1.json
  def show
    @tests = Test.find(:all)
    @test = Test.find(params[:id])
    render

  end
▽show.html.erbの変更

変更前
<p id="notice"><%= notice %></p>

<p>
  <b>Name:</b>
  <%= @test.name %>
</p>


<%= link_to 'Edit', edit_test_path(@test) %> |
<%= link_to 'Back', tests_path %>
変更後
<p id="notice"><%= notice %></p>

<ul id='tests'>
  <%= render({:partial => "test", :collection => @tests}) %>
</ul>

<p>
  <b>Name:</b>
  <span id="test_name">AAAAA</span>
</p>


<%= link_to 'Edit', edit_test_path(@test) %> |
<%= link_to 'Back', tests_path %>
▽_test.html.erbの新規追加
<li><%= link_to test.name, test_path(test)+".js", :remote => true %></li>
▽show.js.erbの新規追加
$("#test_name").html("<%= @test.name %>");
▽サンプルデータの表示の確認

初期状態

クリック後

"XXYYZZ"のリンクをクリックすると、再読み込みなしで、Nameが "XXYYZZ"に変更された。

2012年9月15日土曜日

jQueryを利用したXMLHttpRequestの最小サンプル

jQueryを利用したXMLHttpRequestの最小サンプルを作ってみた。

▽HTML側
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
      $("body").ready(function(){
        $("#disp").load("test.xml");
      })
    </script>
  </head>
  <body>
    <div id="disp"></div>
  </body>
</html>
▽取得するXML
<?xml version="1.0" encoding="UTF-8"?>
<test>GHIJK</test>
▽実行結果
GHIJK
同じことをやるのにフレームワークなしのJavaScriptの場合よりもずいぶん短くなった。

2012年9月2日日曜日

XMLHttpRequestの最小サンプル

XMLHttpRequestの最小サンプルを作ってみた。

▽HTML側
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    
    <script type="text/javascript">
    //<![CDATA[
    function onLoad() {
      var xmlhttp = false;
      if(typeof ActiveXObject != "undefined"){
        try {
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
          xmlhttp = false;
        }
      }
      if(!xmlhttp && typeof XMLHttpRequest != "undefined") {
        xmlhttp = new XMLHttpRequest();
      }

      xmlhttp.open("GET", "./test.xml");
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          var disp = document.getElementById("disp");
          var xmlDoc = xmlhttp.responseXML;
          disp.innerHTML = xmlDoc.getElementsByTagName('test')[0].firstChild.nodeValue;
        }
      }
      xmlhttp.send(null);
    }
    //]]>
    </script>
  </head>
  <body onload="onLoad()">
    <div id="disp">
</div>
</body>
</html>
▽取得するXML
<?xml version="1.0" encoding="UTF-8"?>
<test>ABCDEF</test>
▽実行結果
ABCDEF
▽課題
1.  ローカルのフォルダにファイルを置いただけでは動かない。Webサーバへのアップロードが必要。
2. XMLの値を変更してHTMLファイルをリロードしても、キャッシュのせいで値が更新されない。