LoginSignup
0
0

More than 5 years have passed since last update.

[Javascript] jQueryとprototype.jsが競合してエラーになるときの解決方法

Last updated at Posted at 2015-09-17

ちょっとレガシーなWebサイトをいじっててハマったのでめも。

prototype.jsを使っている既存のコードで以下のようなエラーが発生

Uncaught TypeError: element.dispatchEvent is not a function
Uncaught TypeError: element.attachEvent is not a function
Uncaught TypeError: element.attachEvent is not a function

これの原因はjQueryとprototype.jsでグローバル変数"$"が
jQueryによって上書きされていることによるものだった。

jQueryもprototype.jsも"$" をグローバルスコープで使うライブラリなので、
両方共存させるときはちょっと工夫しなければならない

jQueryの方には、
jQuery.noConflict()
というメソッドが用意されているのでこれを使う。
http://semooh.jp/jquery/api/core/jQuery.noConflict/_/

jQuery.noConflict();
// prototype.jsを使ったコード

これで解決

おまけ
"$" がjQueryのものか、prototypeのものかわからなくなったら、
以下の方法で確認できる

console.log($ === jQuery);

trueなら$はjQuery, falseならprototype.js

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0