スキップしてメイン コンテンツに移動

投稿

ラベル(javascript)が付いた投稿を表示しています

eslintのエラー「describe is not defined when installing jest」の解消法

Jestでテストを書く際にdescribe functionを使うと、describe functionが定義されていないので「‘describe’ is not defined.(no-undef)」というeslintのエラーが出ることがありますが、eslint.jsに下記の設定を追加すれば解消します。 "env" : { "jest" : true } 同様にmocha関連のfuncionを使用した際にも「‘xxxxxx’ is not defined.(no-undef)」などが出ることがありますが、これも "env" : { "mocha" : true } と追記すれば解消します。

JavascriptのObject Literalを使った条件分岐

条件分岐を簡潔に書きたい! 条件分岐をする場合、通常はif~else文やswitch~case文を使うことが一般的ですが、Object Literalを活用すると簡潔にコードを書くことできる場合があります。Object Literalを利用するのは、ちょうどPHPのarray、JavaのMap、C#のDictionaryなどの連想配列を利用するイメージが近いと思います。 switch~case文とObject Literalを使った場合のコード例をいくつか示していきます。 switch~case文とローカル変数を使った場合 function GetStockCode_LocalVariable ( makerName ) { let code = "" ; switch ( makerName ) { case "Asus" : code = "2557" ; break ; case "MSI" : code = "2377" ; break ; default : throw new Error ( "unsupported maker: " + makerName ) ; } console . log ( code ) ; } 一般的な書き方ですが、下記の短所があります。 mutableなローカル変数のcodeを定義しなければならない。 switch~caseのキーワードやbreakキーワードが何度も出現し、重要な部分がわかりにくい switch~case文と即時実行関数式(Immediately Invoked Function Expression)を使った場合 function GetStockCode_IIFE ( makerName ) { const code = ( ( ) => { switch ( m

Javascriptで動作するHTMLエディター

Web画面上でHTMLを編集するために、Javascript実装のHTMLエディタが必要になることがあると思います(例えばWordpressやBloggerのエディタのようなものです)。 様々なエディタがありますが、 Code Mirror というエディタは高機能で便利です。下記のような機能があります。 100以上の言語をサポート 強力なxmlタグ補完機能 コード折り畳み機能 Vim、Emacsなどと同じキーバインディングのサポート 検索・置換機能 括弧、タグのマッチング機能 たくさんのアドオン

Javascript Html 5 Canvas: Visualize CSV 2 Dimensional Data

Motivation: Visualize 2 Dimensional Data with Lightweight Way I wrote small java program for calculating Jaccard Similarity among source code in this post . And map into them 2 dimensional map using Multi Dimensional Scaling technique. I have used MDSJ – Multidimensional Scaling for Java . (By the way the library is quite simple and meet my requirement perfectly!! Excellent!!)> Next step is how to visualize the bunch of 2 dimensional (x,y) coordinate data so that human can easily understand. Of course, I am good at Java, I can write some code for visualize data in Java using Swing or Java FX etc. But it's not lightweight way. So, I decided to use HTML5 Canvas + Javascript. Viewer: Html5 Canvas + Javascript The features of the Data Viewer are: Visualize CSV data Expected 3 columns without header row: name

Check Black List Words in Files by Bash Script

I wrote tiny bash script for checkin files contains black listed words or not. The aim of this script is to automate verifying php or javascript files does not have any debugging code, such as "var_dump","alert" etc. #!/bin/bash PHP_BLACK_LIST_WORDS=("var_dump(") JAVASCRIPT_BLACK_LIST_WORDS=("alert(") verify_words_are_not_contained(){ words="$1" len=${#words[@]} if [ $len -ge 0 ] then grep_words="" for word in "${words[@]}" do grep_words+="$word\|" done # remove last 2 characters grep_words=${grep_words%?} grep_words=${grep_words%?} grep_command="grep \"$grep_words\" $2 -nr --include=$3 > $OUTPUT_DIR/$4" echo "running $grep_command" eval $grep_command fi } setup_output_dir(){ target_dir_name=${1##*/} OUTPUT_DIR=$target_dir_name"_detected_black_list_words" echo "$OUTPUT_DIR" rm -r -f

Loading Javascript On Demand (When User Click Button etc.)

Recently, everyone must know placing js script tag at the bottom of html or using "async" attribute so that the page can be rendered not blocked by the scripts loading or excecution. In this post, I will exaplain how to load javascript on demand - e.g. event based. The technique is applicable when javascript is loaded only for a event - like after click button. The usecase might be limited and code becomes a bit complicated so I suggest you should only use this technique at the situation: The script doesn't have to be loaded on user' initial page load. The script is loaded only when user do some interaction on the page - like click button, etc. Most user doesn't trigger the event. That is, if most user trigger the event, then you should simply write script tag. Ok, then now I will show you the code and demo. $(function(){ var scriptLoaded = false; $("#load_button").click(function (){ if (!scriptLoaded) { sc

Loading Facebook Like Button Faster

In this post, I will explain how to load facebook like button faster. The Official Method Explained on Facebook The official method to load Facebook Button for HTML5 is below. There is another option - using iframe. See below. In my experience, using iframe is relatively faster than using HTML5. I think it's because if we use the HTML5 method, the facebook javascript SDK should be loaded before rendering the like button. Actually, this is important fact, even if you choose the html5 way to load like button, the loaded like button is iframe in the end. So question comes up - "What about load iframe like button manually by my self wrinting javascript?". Loading ifram Like Button by Javascript The below code shows loading iframe like button by javascript. To be honest nothing special at all - create iframe like button and append it to html by javascript. $(function(){ $("#fblike").append(createLike("http://dukesoftware00.blogspot.com"

Get Youtube Video Detail Information Only Using Javascript

Demo URL Title Duration (Sec) View Count Source code <table border="1"> <tbody> <tr> <td>URL</td> <td><input type="text" id="youtubeVideo_url" style="width:100%"></td> </tr> <tr> <td>Title</td> <td><div id="youtubeVideo_title"></div></td> </tr> <tr> <td>Duration (Sec)</td> <td><div id="youtubeVideo_duration_seconds"></div></td> </tr> <tr> <td>View Count</td> <td><div id="youtubeVideo_view_count"></div></td> </tr> </tbody> </table> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $("#youtubeVideo_url").keyup(function(e){ delay(function(){ var url = $('#yout

Javascript: Lazy Load Image

I realized that most of the modern browser download the image which is set on src attribute even if the img element is hidden. This sometimes goes to performance problem because even if there are a lot of hidden image which are only shown user interacts, all images are downloaded initial page load! So I wrote a simple javascript for reflesh the src attribute and download image only when user interacts somethig on window - like press button etc. I know you can use JQuery LazyLoad plugin , but I would like to take much more faster solution - no external javascript. Here is the demo. When you push the button, the image is loaded lazyly Load image Here is the key method. (maybe you can check the logic by viewing the src directly though.) Replace the src attribute with data-original attribute i the img tag. function loadImage(elem) { if(elem.attr("src") != elem.attr("data-original")) { elem.attr("src", elem.attr("data-original&qu

Build Get Parameter String from Javascript Object or Map

This is just a quick tips... I think you can easily understand whole thing from the code below. // example data used for get parameters. You can use plain javascript object if you want. var map = ["name1":"value1", "name2":"value2"]; // Ok, let’s build string... var parameters = []; for(var prop in map) { // if the name part (prop) contains the characters to uri encode, // use encodeURIComponent as well for the name part. parameters.push(prop + "=" + encodeURIComponent(map[prop])); } var parametersStr = parameters.join("&");

Check window.opener permission

Issue I tried to access some properties (or call methods) defined in http parent window via window.opener in pop-upped https window, which is created from the parent window. But it simply fails when accessing window.opener.a_property in the child window because the protocol is different between the child and parent window. e.g. http and https Remember this browser behavior is absolutely correct. The point of this post is how to avoid simply stopping javascript when accessing properties in window.opener. Browsers I confirmed this permission issue happens FireFox 17.0.1 and Internet Explore 9. Somehow Chrome doesn't complain it at all. the code simply passed. Solution In order to avoid this, I wrote the following conditions to detect the window.opener is accessible or not before accessing window.opener, but all of them don't return expected result at all. if(window.opener) // return true :( if(window.opener == undefined) // return true :( Finally I have reached at

JsTestDriver Trouble and Tips

I am looking for testing tools for Javascript and reached at This Stackoverflow page . The page contains bunch of useful information :) After reading the page, I decided to use JsTestDriver for the following reason. having high affinity with CI server providing plugin for codecoverage - ( lcov format) JUnit format report To run Javascript test, you need to start up JsTestDriver server. The command is simple. java -jar JsTestDriver-1.3.4.b.jar --port 9876 One thing you should be careful about is if you run the above command in the directory which includes jsTesDriver.conf, the jar automatically picked up the jsTestDriver.conf and and it starts as server mode. Ok now you need to run client side (actual tests) against the server. You will use FireFox + Xvfb or PhantomJS as headless browser. java -jar JsTestDriver-1.3.4.b.jar --browser {path to browser} --tests all --config jsTestDriver.conf --testOutput testResult Also jsTestDriver.conf should something like this: server:

Selenium IDEの使い勝手について調査

Selenium IDEの概要 FireFoxのPlugin 公式ドキュメント 独断と偏見に満ちた長所・短所 長所 作成したテストを様々なプログラミング言語で出力可能 (File->Export Test Suite As...) ブラウザ上での操作をSelenium IDE Commandとして記録するマクロ機能あり 短所 正直、このpluginを導入するより、普通のSeleniumを使って、システムの実装言語だけでテストが完結している方が、プロジェクトの運用コストや学習コストが低くてすむ可能性大。 スクリプトを書いてみた感じだと'''面倒くさい'''。後々のテストのメンテナンスに難あり。 その他、メモ Html内の要素の選択方法 XPath, CSS, DOM, id属性, name属性などが使える Selenium CoreのLocatorsを参照 Assertion or Verification? Assert: テストに失敗すると、それ以降のテストコマンドは実行されない Verify: テストに失敗すると、結果はFailとして表示されるが、Verify以降のテストコマンドは引き続き実行される waitForコマンドは特定の要素が出現するまで待って、出現したら次のテストコマンドを実行する。Ajax系のテストに最適。

PMD and CPD for ECMAScript (Javascript)

Recently I have tried to use PMD and CPD for Javascript. I found that the offical PMD release says PMD 5.0.0 supports Javascript :D We have strong code inspection tools like Sonar etc. But I think still helpful for setting up compact ant task. PMD PMD ant task setup for javascript is easy, almost same as Java. Only you have to remember is including rhino jar in the classpath. Here is the example. <property name="buildscripts.path" location="${basedir}/generic-buildscripts"/> <property name="pmd.jar" value="pmd-5.0.0.jar"/> <property location="rhino-1.7R3.jar" name="rhino.jar"/> <path id="pmd.classpath"> <fileset dir="${buildscripts.path}/pmd/"> <include name="asm-3.2.jar"> <include name="jaxen-1.1.1.jar"> <include name="${pmd.jar}"> <include pa

Javascript + HTML5を使った画像処理

HTML5のcanvasエレメントを使うと画像のピクセル処理ができると知りまして、試しにJavascriptで画像処理プログラムを書いてみました。 「画像処理なんてServer Sideでやれよ!」とか「なんでC++ではなくてJavascript?」というご指摘もありそうですがご容赦のほどを。 デモを公開 しました。 注意点など   デモを見るにはHTML5対応のブラウザが必要(当たり前)。  サイズの大きなメディアンフィルタのデモは少し時間がかかるので、気長に待ってください。  サーバサイド側では何もしていません。興味のある方はhtmlのソースを見てください。役に立ちそうなら、勝手に使っちゃってください。(でもこのブログにリンクとか張ってくれると、とても嬉しいです。)  今のところ以下の処理が選択できます。がんばって増やします!! 輝度変換 グレースケール化(YUV画像ののY値信号のみ取り出し) メディアンフィルタ(3x3, 5x5, 7x7) 判別分析法による2値化 Prewitt Filter Sobel Filter Laplacian Filter Sharpening Filter LOG Filter(エッジ検出)  今後、試したい処理 Gammaカーブ変更 コーナー検出 ハフ変換 パターンマッチング アフィン変換 画像のResampling フーリエ変換 バイラテラルフィルタ ラベリング ソースコード例 上記のURLからソースコードを読むと余計なコードが入っていますので、純粋に画像処理部分だけ抜き出したコードを下に示します。 興味がある方は、サンプルサイトのソースコードを読んでみてください。 判別分析法による2値化 function binalyze(srcRgbImageData, destImageData) { var step = 4; var LEN = 256, MAX=255; var srcRgb = srcRgbImageData.data; var dest = destImageData.data; var imgWidth = srcRgbImageData.width; v

Javascriptで実装された画像ギャラリーライブラリ

(2020年5月更新) こちらの下記理由により、デモを非公開にしました。 picasaはもうGoogle Photosに統合されてAPIが変わった。 Gallerifficももうアクティブに開発されていない。JQueryのプラグイン化されたようです。 記録目的で記事は残してあります。 Javascriptで実装された画像ギャラリーのライブラリ集です。 試しにいくつか使ってみた中で実際に使えると思ったものを選びました。 他にもかっこいいものがいっぱいあるのですが、実際使うとなると、なかなか厳しい(=使いにくい)ものも多いです。 最近はブラウザのJavascriptエンジンの性能も上がっていますし、HTML5やCSS3も徐々に浸透してきていますので、 ブラウザでお手軽に見栄えのするものが作れるのが魅力かなと思います。 注意点をいくつか。 上記のデモの場合、1つのオリジナル画像につき、「75px程度の正方形にクロップされた画像」と「幅が500px程度にサイズ変更された画像」の2つが必要です。 Picasaについては画像サイズを指定してクエリを投げられるので、ちょうどよい大きさの画像のクエリを作成して投げれば簡単にサムネイルが画像を取得できます。 肝はデモで使っているURLの https://picasaweb.google.com/data/feed/api/all?alt=rss&kind=photo&thumbsize=72c,512&access=public&imgmax=1600&hl=en_US&max-results=50 のthumbsize=72c,512の部分です。 簡単に説明しますと、サイズの後にcをつけると画像を正方形にクロップしてくれます。何もつけないとアスペクト比を固定して画像をリサイズしてくれます。 詳しく知りたい方は Picasa Data APIの公式ドキュメント を参照してください。 自分で大量の画像のサイズ変更するのは面倒くさいと思います。私の場合はJavaやC#で画像サイズを変更するプログラムを書きました。バッチ処理が可能な画像処理用のソフトを使うのもいいかもしれません。 C#のコードは簡潔で、実行性能もいいので載せておきます。画像を指定したサイズの正方形

Flatten JSON object to html ul & li items by Javascript

I have written Javascript code snippet which can flatten JSON object to html ul and li items. Please see this example . The example demonstrates flattening the following JSON object. { "Name":"Duke", "Birth Year": 1876, "Skill":{ "Java":"Wizard (hopefully)", "C#":"Master (kidding)", "F#":"Beginner (No!)" }, "Favorite":["Violin", "Programming"] } Actual Javascript code is something like this: // original data var person = { "Name":"Duke", "Birth Year": 1876, "Skill":{ "Java":"Wizard (hopefully)", "C#":"Master (kidding)", "F#":"Beginner (No!)" }, "Favorite":["Violin", "Programming"] } window.onload = function(){ try{ writeAsHtml(person,

html読み込みの進捗状況を表示するjavascriptのプログレスバー

以下のコードの coutUp functionをhtmlの途中に埋め込むことで、そのhtmlページの読み込みの進捗状況を表示することができます。(こういう方法がいいかどうかはわかりませんが。) function ProgressBar(id) { this.div = setProgressDIV(id); this.init = init; this.countUp = countUp; var progress; function setProgressDIV(id) { if(!id){ id = "_progress"+(new Date()).getTime(); var creprgDIV = document.createElement("DIV") ; this.div = document.body.appendChild(creprgDIV) ; this.div.setAttribute("id",id) ; this.div.style.position = "relative"; this.div.style.top = "0px"; this.div.style.left = "0px"; this.div.style.width = "0px"; this.div.style.height = "0px"; } else { this.div = document.getElementById(id) } this.div.style.color = 'blue' ; this.div.style.margin = '0px' ; this.div.style.padding = '4px'; this.div.prog_bar= '|'; this.div.prog_count

JavascriptでProgressBarを実装

Javascriptで簡単な プログレスバー を実装してみました!ソースコードは以下の通りです。 function ProgressBar(id, max_count, bar_char, color) { this.div = setupProgressDIV(id, max_count, bar_char, color); this.startProgress = startProgress; this.stopProgress = stopProgress; this.finish = finish; var finishFlag = 0; function setupProgressDIV(id, max_count, bar_char, color) { if(!id){ id = "_progress"+(new Date()).getTime(); if(document.getElementsByTagName('BODY').length==0) document.write('<body>') var creprgDIV = document.createElement("DIV") ; this.div = document.body.appendChild(creprgDIV) ; this.div.setAttribute("id",id) ; this.div.style.position = "relative"; this.div.style.top = "0px"; this.div.style.left = "0px"; this.div.style.width = "0px"; this.div.style.height = "0px"; } else { this.div = document.