Como usar jQuery sem conflito com outras bibliotecas JavaScript
Estava trabalhando em uma página que já fazia o uso da biblioteca jQuery para apresentação de alguns componentes, contudo surgiu a necessidade de usar ajax nessa mesma página. Apesar da jQuery possuir um bom suporte para ajax, eu gosto muito também da prototype, pois além de ter mais prática (com ajax), também já tenho algumas customizações prontas.
Após incluir a prototype e testar a página, percebi que um erro de JavaScript estava ocorrendo, no começo achei que a causa do erro era em razão de uma função – usando a prototype – que eu tinha acabado de fazer, mas depois usando o bem dito firebug e fazendo alguns debugs, percebi que o erro era mesmo em um conflito entre a jQuery e a prototype.
O problema ocorre, pois as duas bibliotecas fazem o uso da função “$()” para acessar as suas funções, o que acaba gerando o conflito.
A biblioteca jQuery fornece algumas maneiras de resolver isso, mas todas giram em torno da função jQuery.noConflict(). A solução que oferece o maior custo x benefício na minha opinião, é a que eu não preciso alterar os meus métodos já existentes, ou seja, não precisaria ter que fazer isso:
var $j = jQuery.noConflict();
$j("div").hide();
No caso acima, se eu já tivesse N funções usando jQuery, eu precisaria fazer uma refatoração do meu código para mudar o método “chamador” das minhas funções de $() para $j(), isso geraria algum tempo perdido com muitas mudanças e muitos testes. A solução que encontrei pede apenas para que as funções fiquem dentro da document ready area da jQuery, então ficaria mais ou menos assim:
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
jQuery.noConflict();
// Put all your code in your document ready areajQuery(document).ready(function($){
// Do jQuery stuff using $$("div").hide();
});
// Use Prototype with $(...), etc.$('someid').hide();
</script>
Da maneira acima eu não precisaria mudar nenhuma função já existente, bastaria apenas incluí-las dentro do bloco indicado.
Segundo a documentação, essa seria a solução mais adequada na maioria dos casos.
Se você gostou desse tópico, por favor considere deixar um comentário ou se inscreva no feed e tenha no futuro todos os tópicos entregues diretamente no seu agregador.








Olá!
Crio templates para o Blogger, mas sou autodidata completamente leiga com scripts, mas instalei um script “Page Peel” em um template e, não faço a menor idéia de porque tenha simplesmente parado de funcionar (olha não rí que eu to vendo) rsss
Caso voce possa me ajudar a entender o conflito que está havendo, ficarei grata. Caso não queira resposnder, fico grata do mesmo jeito
o template está em:
http://www.mamanestes1.blogspot.com
Um abraço!
Mamanunes
Ótimo artigo cara me ajudou muito parabéns!
Marcos, obrigado pela dica. Há algum tempo vinha sofrendo com esses conflito de $(). Seu tutorial foi de grande ajuda. Obrigado. Sucesso pra você.
Gando abraço.
Esse método ainda é falho.
E por que?
pq é falho? traga a solução. o cara entra e só fala que é falho mas nao ajuda em merda nenhuma.
Cara valeu muito, esse teu post, foi o único que deu a uma solução que realmente funciona, estava usando prototype e depois tive de inclur jquery e após muita pesquisa o único que teve um solução que funcionou foi a tua.
Fiquei uma tarde tentando entender porque meus codigos não funcionavam, mas depois de ler este artigo, funfo tudo direitinho.
Aleluiaaaaaaaaaaaa
Tava usando o “prototype” ai coloquei um outro código usando o “jQuery” mais a partir desse ponto o “prototype” tinha parado de funcionar…
Foi só colocar isso dentro do código que funcionou os 2.
var $j = jQuery.noConflict();
$j(“div”).hide();
Ai muda o valor do jQuery que é $ para $j
Tão simples e eu tava louco achando que iria ter que tirar um e só deixar o outro!
Valeu tu me salvou! xD
esta solução foi perfeita!
It certainly is not common to obtain this type of unique outtake. A lot of blog owners usually are not as concentrated…
estou com problemas com o prototype, não consigo encontrar a solução sempre dá erro nessas linhas:
element.attachEvent(“on” + name, wrapper);
element.fireEvent(event.eventType, event);
coloquei o código que foi falado aqui mais um funciona e outro para de funcionar. Agradeço desde já pela atenção
Mano do Céu !!!!!!!!
Salvou meu dia !!!!!!!!
te pagaria uma caixa de cerveja !!!!!
huahuahuahuahua
Deus te abençoe
Muito bom! nem terminei d eler e to elogiando!!
Vai me ajudar muito!
Não funcionou. Tenho um slider e um lightbox pra rodar na mesma página e ou funciona um ou o outro. nunca os dois.
Sou meio novo com jQuery e fiquei na dúvida de onde exatamente eu deveria inserir essas linhas do “noConflict”. Dentro do jQuery, do prototype ou no head do documento?
Todas as tentativas que eu fiz, com ambos os métodos descritos, não deu muito certo. Ou só 1 funcionava, ou os 2 paravam. Não consegui fazer os 2 funcionarem. Help please!
Rafael, isso vai te ajudar:
http://api.jquery.com/jQuery.noConflict/
Consegui fazer funcionar renomeando todas as minhas funções $ que estavam em conflito, para outra variável que estava sendo atribuída. No caso $j e consegui fazer funcionar.
Vou dar uma lida nesse link que vc passou pra entender melhor o esquema. Obrigado, Marcus!
Olá, eu estou fazendo um blog com WordPress e estou tendo problemas com os plugins que instalei. Já andei pesquisando e pelo o que eu entendi é conflito de jquery. Já olhei vários tutoriais falando sobre isso mas não consegui resolver, eu simplesmente não sei onde que tenho que colocar esse código… Tenho muitas páginas, e já fiz vários testes e não funcionou… Acredito que não tenho colocado no lugar certo… Vc pode me ajudar? ;-)
Opa achei bastante interessante, mais não funcionou para o meu caso
ele esta em conflito com banners rotativos
o erro é este
var as = $(‘links’).getElementsByTagName(‘a’);
att.
Brambilla
OK
resolvi o problema
att.
Brambilla
Cara … fiz o que você informou no segundo exemplo.
Mas o que ocorreu foi: minha página não carrega nada. Nem mesmo o conteúdo.
O que pode ser?
Cara … fiz o que você informou no segundo exemplo.
Mas o que ocorreu foi: minha página não carrega nada. Nem mesmo o conteúdo.
O que poderia ocasionar isso?
Fiz do primeiro modo e funcionou. Estava usando o lightbox e slider vertical com um código bem simples, dai alterei esse código mesmo, só dei um CTRLF em $( e mandei substituir por $j(.
Funcionou na primeira! Valeu mesmo cara, abraço!
não entendi nada, não especifica onde colar, e que área especificada é essa? Não me judou muito porque não sei nada de jquery. :|
Muito obrigado amigo, resolveu o meu problema também.
Muito obrigado Marcus!
Funcionou PERFEITAMENTE!
pessoal to com este problemão aki, e não ta rodando por causa do é o picareta do código, alguem pode ajudar…. obrigado…
/*
the images preload plugin
*/
(function($) {
$.fn.preload = function(options) {
var opts = $.extend({}, $.fn.preload.defaults, options),
o = $.meta ? $.extend({}, opts, this.data()) : opts;
return this.each(function() {
var $e = $(this),
t = $e.attr(‘rel’),
i = $e.attr(‘href’),
l = 0;
$(”).load(function(i){
++l;
if(l==2) o.onComplete();
}).attr(‘src’,i);
$(”).load(function(i){
++l;
if(l==2) o.onComplete();
}).attr(‘src’,t);
});
};
$.fn.preload.defaults = {
onComplete : function(){return false;}
};
})(jQuery);
$(function() {
//some elements..
var $ps_container = $(‘#ps_container’),
$ps_image_wrapper = $ps_container.find(‘.ps_image_wrapper’),
$ps_next = $ps_container.find(‘.ps_next’),
$ps_prev = $ps_container.find(‘.ps_prev’),
$ps_nav = $ps_container.find(‘.ps_nav’),
$tooltip = $ps_container.find(‘.ps_preview’),
$ps_preview_wrapper = $tooltip.find(‘.ps_preview_wrapper’),
$links = $ps_nav.children(‘li’).not($tooltip),
total_images = $links.length,
currentHovered = -1,
current = 0,
$loader = $(‘#loader’);
/*check if you are using a browser*/
var ie = false;
if ($.browser.msie) {
ie = true;//you are not!Anyway let’s give it a try
}
if(!ie)
$tooltip.css({
opacity : 0
}).show();
/*first preload images (thumbs and large images)*/
var loaded = 0;
$links.each(function(i){
var $link = $(this);
$link.find(‘a’).preload({
onComplete : function(){
++loaded;
if(loaded == total_images){
//all images preloaded,
//show ps_container and initialize events
$loader.hide();
$ps_container.show();
//when mouse enters the pages (the dots),
//show the tooltip,
//when mouse leaves hide the tooltip,
//clicking on one will display the respective image
$links.bind(‘mouseenter’,showTooltip)
.bind(‘mouseleave’,hideTooltip)
.bind(‘click’,showImage);
//navigate through the images
$ps_next.bind(‘click’,nextImage);
$ps_prev.bind(‘click’,prevImage);
}
}
});
});
function showTooltip(){
var $link = $(this),
idx = $link.index(),
linkOuterWidth = $link.outerWidth(),
//this holds the left value for the next position
//of the tooltip
left = parseFloat(idx * linkOuterWidth) – $tooltip.width()/2 + linkOuterWidth/2,
//the thumb image source
$thumb = $link.find(‘a’).attr(‘rel’),
imageLeft;
//if we are not hovering the current one
if(currentHovered != idx){
//check if we will animate left->right or right->left
if(currentHovered != -1){
if(currentHovered < idx){
imageLeft = 75;
}
else{
imageLeft = -75;
}
}
currentHovered = idx;
//the next thumb image to be shown in the tooltip
var $newImage = $('’).css(‘left’,’0px’)
.attr(‘src’,$thumb);
//if theres more than 1 image
//(if we would move the mouse too fast it would probably happen)
//then remove the oldest one (:last)
if($ps_preview_wrapper.children().length > 1)
$ps_preview_wrapper.children(‘:last’).remove();
//prepend the new image
$ps_preview_wrapper.prepend($newImage);
var $tooltip_imgs = $ps_preview_wrapper.children(),
tooltip_imgs_count = $tooltip_imgs.length;
//if theres 2 images on the tooltip
//animate the current one out, and the new one in
if(tooltip_imgs_count > 1){
$tooltip_imgs.eq(tooltip_imgs_count-1)
.stop()
.animate({
left:-imageLeft+’px’
},150,function(){
//remove the old one
$(this).remove();
});
$tooltip_imgs.eq(0)
.css(‘left’,imageLeft + ‘px’)
.stop()
.animate({
left:’0px’
},150);
}
}
//if we are not using a “browser”, we just show the tooltip,
//otherwise we fade it
//
if(ie)
$tooltip.css(‘left’,left + ‘px’).show();
else
$tooltip.stop()
.animate({
left : left + ‘px’,
opacity : 1
},150);
}
function hideTooltip(){
//hide / fade out the tooltip
if(ie)
$tooltip.hide();
else
$tooltip.stop()
.animate({
opacity : 0
},150);
}
function showImage(e){
var $link = $(this),
idx = $link.index(),
$image = $link.find(‘a’).attr(‘href’),
$currentImage = $ps_image_wrapper.find(‘img’),
currentImageWidth = $currentImage.width();
//if we click the current one return
if(current == idx) return false;
//add class selected to the current page / dot
$links.eq(current).removeClass(‘selected’);
$link.addClass(‘selected’);
//the new image element
var $newImage = $(”).css(‘left’,currentImageWidth + ‘px’)
.attr(‘src’,$image);
//if the wrapper has more than one image, remove oldest
if($ps_image_wrapper.children().length > 1)
$ps_image_wrapper.children(‘:last’).remove();
//prepend the new image
$ps_image_wrapper.prepend($newImage);
//the new image width.
//This will be the new width of the ps_image_wrapper
var newImageWidth = $newImage.width();
//check animation direction
if(current > idx){
$newImage.css(‘left’,-newImageWidth + ‘px’);
currentImageWidth = -newImageWidth;
}
current = idx;
//animate the new width of the ps_image_wrapper
//(same like new image width)
$ps_image_wrapper.stop().animate({
width : newImageWidth + ‘px’
},350);
//animate the new image in
$newImage.stop().animate({
left : ’0px’
},350);
//animate the old image out
$currentImage.stop().animate({
left : -currentImageWidth + ‘px’
},350);
e.preventDefault();
}
function nextImage(){
if(current 0){
$links.eq(current-1).trigger(‘click’);
}
}
});
não foi direito, mas acho que agora vai…
/*
the images preload plugin
*/
(function($) {
$.fn.preload = function(options) {
var opts = $.extend({}, $.fn.preload.defaults, options),
o = $.meta ? $.extend({}, opts, this.data()) : opts;
return this.each(function() {
var $e = $(this),
t = $e.attr(‘rel’),
i = $e.attr(‘href’),
l = 0;
$(”).load(function(i){
++l;
if(l==2) o.onComplete();
}).attr(‘src’,i);
$(”).load(function(i){
++l;
if(l==2) o.onComplete();
}).attr(‘src’,t);
});
};
$.fn.preload.defaults = {
onComplete : function(){return false;}
};
})(jQuery);
$(function() {
//some elements..
var $ps_container = $(‘#ps_container’),
$ps_image_wrapper = $ps_container.find(‘.ps_image_wrapper’),
$ps_next = $ps_container.find(‘.ps_next’),
$ps_prev = $ps_container.find(‘.ps_prev’),
$ps_nav = $ps_container.find(‘.ps_nav’),
$tooltip = $ps_container.find(‘.ps_preview’),
$ps_preview_wrapper = $tooltip.find(‘.ps_preview_wrapper’),
$links = $ps_nav.children(‘li’).not($tooltip),
total_images = $links.length,
currentHovered = -1,
current = 0,
$loader = $(‘#loader’);
/*check if you are using a browser*/
var ie = false;
if ($.browser.msie) {
ie = true;//you are not!Anyway let’s give it a try
}
if(!ie)
$tooltip.css({
opacity : 0
}).show();
/*first preload images (thumbs and large images)*/
var loaded = 0;
$links.each(function(i){
var $link = $(this);
$link.find(‘a’).preload({
onComplete : function(){
++loaded;
if(loaded == total_images){
//all images preloaded,
//show ps_container and initialize events
$loader.hide();
$ps_container.show();
//when mouse enters the pages (the dots),
//show the tooltip,
//when mouse leaves hide the tooltip,
//clicking on one will display the respective image
$links.bind(‘mouseenter’,showTooltip)
.bind(‘mouseleave’,hideTooltip)
.bind(‘click’,showImage);
//navigate through the images
$ps_next.bind(‘click’,nextImage);
$ps_prev.bind(‘click’,prevImage);
}
}
});
});
function showTooltip(){
var $link = $(this),
idx = $link.index(),
linkOuterWidth = $link.outerWidth(),
//this holds the left value for the next position
//of the tooltip
left = parseFloat(idx * linkOuterWidth) – $tooltip.width()/2 + linkOuterWidth/2,
//the thumb image source
$thumb = $link.find(‘a’).attr(‘rel’),
imageLeft;
//if we are not hovering the current one
if(currentHovered != idx){
//check if we will animate left->right or right->left
if(currentHovered != -1){
if(currentHovered < idx){
imageLeft = 75;
}
else{
imageLeft = -75;
}
}
currentHovered = idx;
//the next thumb image to be shown in the tooltip
var $newImage = $('’).css(‘left’,’0px’)
.attr(‘src’,$thumb);
//if theres more than 1 image
//(if we would move the mouse too fast it would probably happen)
//then remove the oldest one (:last)
if($ps_preview_wrapper.children().length > 1)
$ps_preview_wrapper.children(‘:last’).remove();
//prepend the new image
$ps_preview_wrapper.prepend($newImage);
var $tooltip_imgs = $ps_preview_wrapper.children(),
tooltip_imgs_count = $tooltip_imgs.length;
//if theres 2 images on the tooltip
//animate the current one out, and the new one in
if(tooltip_imgs_count > 1){
$tooltip_imgs.eq(tooltip_imgs_count-1)
.stop()
.animate({
left:-imageLeft+’px’
},150,function(){
//remove the old one
$(this).remove();
});
$tooltip_imgs.eq(0)
.css(‘left’,imageLeft + ‘px’)
.stop()
.animate({
left:’0px’
},150);
}
}
//if we are not using a “browser”, we just show the tooltip,
//otherwise we fade it
//
if(ie)
$tooltip.css(‘left’,left + ‘px’).show();
else
$tooltip.stop()
.animate({
left : left + ‘px’,
opacity : 1
},150);
}
function hideTooltip(){
//hide / fade out the tooltip
if(ie)
$tooltip.hide();
else
$tooltip.stop()
.animate({
opacity : 0
},150);
}
function showImage(e){
var $link = $(this),
idx = $link.index(),
$image = $link.find(‘a’).attr(‘href’),
$currentImage = $ps_image_wrapper.find(‘img’),
currentImageWidth = $currentImage.width();
//if we click the current one return
if(current == idx) return false;
//add class selected to the current page / dot
$links.eq(current).removeClass(‘selected’);
$link.addClass(‘selected’);
//the new image element
var $newImage = $(”).css(‘left’,currentImageWidth + ‘px’)
.attr(‘src’,$image);
//if the wrapper has more than one image, remove oldest
if($ps_image_wrapper.children().length > 1)
$ps_image_wrapper.children(‘:last’).remove();
//prepend the new image
$ps_image_wrapper.prepend($newImage);
//the new image width.
//This will be the new width of the ps_image_wrapper
var newImageWidth = $newImage.width();
//check animation direction
if(current > idx){
$newImage.css(‘left’,-newImageWidth + ‘px’);
currentImageWidth = -newImageWidth;
}
current = idx;
//animate the new width of the ps_image_wrapper
//(same like new image width)
$ps_image_wrapper.stop().animate({
width : newImageWidth + ‘px’
},350);
//animate the new image in
$newImage.stop().animate({
left : ’0px’
},350);
//animate the old image out
$currentImage.stop().animate({
left : -currentImageWidth + ‘px’
},350);
e.preventDefault();
}
function nextImage(){
if(current 0){
$links.eq(current-1).trigger(‘click’);
}
}
});
desculpa pessoal ultima tentativa, se alguem poder ajudar…
/*
the images preload plugin
*/
(function($) {
Bom, eu to com um problema parecido e fiz o que voce fez ai, mas nao deu certo. Se puderes me passar seu e-mail para eu passar o codigo, ai quem sabe voce conseguiria me ajudar melhor.
Muito obrigado
Onde inserir esse código abaixo no meu template para corrigir esse conflito que ocorre com as galerias jquery:
jQuery.noConflict();
// Put all your code in your document ready area
jQuery(document).ready(function($){
// Do jQuery stuff using $
$(“div”).hide();
});
// Use Prototype with $(…), etc.
$(‘someid’).hide();