Conflict between two js scripts, I can't understand why? - javascript

I am trying to implement a tracking script that standalone and on other sites works just as intended (or atleast to what I can see from watching the sites and analytics).
The code looks like this
{
jQuery(document).ready(function($) {
var filetypes = /\.(zip|exe|dmg|pdf|doc.*|xls.*|ppt.*|mp3|txt|rar|wma|mov|avi|wmv|flv|wav)$/i;
var baseHref = '';
if (jQuery('base').attr('href') != undefined) baseHref = jQuery('base').attr('href');
jQuery('a').on('click', function(event) {
var el = jQuery(this);
var track = true;
var href = (typeof(el.attr('href')) != 'undefined' ) ? el.attr('href') :"";
var isThisDomain = href.match(document.domain.split('.').reverse()[1] + '.' + document.domain.split('.').reverse()[0]);
if (!href.match(/^javascript:/i)) {
var elEv = []; elEv.value=0, elEv.non_i=false;
if (href.match(/^mailto\:/i)) {
elEv.category = "Email";
elEv.action = "Klick";
elEv.label = href.replace(/^mailto\:/i, '');
elEv.loc = href;
}
else if (href.match(filetypes)) {
var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
elEv.category = "Nerladdning";
elEv.action = "Fil-" + extension[0];
elEv.label = href.replace(/ /g,"-");
elEv.loc = baseHref + href;
}
else if (href.match(/^https?\:/i) && !isThisDomain) {
elEv.category = "Ex.Länk";
elEv.action = "Klick";
elEv.label = href.replace(/^https?\:\/\//i, '');
elEv.non_i = true;
elEv.loc = href;
}
else track = false;
if (track) {
_gaq.push(['_trackEvent', elEv.category.toLowerCase(), elEv.action.toLowerCase(), elEv.label.toLowerCase(), elEv.value, elEv.non_i]);
if ( el.attr('target') == undefined || el.attr('target').toLowerCase() != '_blank') {
setTimeout(function() { location.href = elEv.loc; }, 400);
return false;
}
}
}
});
});
}
This is the jquery version that is loaded before
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js"></script>
Now onto the problem, if I place "my" script above the ones I will post below then my script works. But if I do it as I want, placing my script last on the page it does not work, or anywhere aslong as it is below the other one will end up with mine not working
<script type="text/javascript"> jQuery(document).ready(function ($) { runJS(); }); </script>
The runJS leads to another .js file that is functions.js, of what I can understand runJS is this (I replaced the name of the site with site below).
function runJS() {
if((fontLoaded('DistrictThin') && fontLoaded('NationalLight')) || timer > 30) {
site.init();
$(".search_result").find('img').load(function () {
$(".search_result.primary").equalHeights();
//$(".search_result:not(.primary)").equalHeights();
});
if ($('#site_search_form').length > 0) {
populateForm();
}
}
else {
setTimeout('runJS()', 100);
timer += 1;
}
}
Any help would be much appreciated!

if you using different version of jquery in single page you must use this
var jq = jQuery.noConflict (); // jq having the value of $.
// In your entire script use jq instead of $.

Related

Can't get each to work after ajax page load changes contents

on page load I run this function to hide long quoted posts into a clickable link to prevent huge comments on my site:
function hide_long_quotes()
{
$('.comments .comment_quote').each(function(i)
{
var actual_text = $(this).text();
var content = $(this).outerHTML();
if(actual_text.length > showChar)
{
var cite = $(this).find('cite span.username').first().text();
var cite_link = '';
if (cite.length > 0)
{
cite_link = 'from ' + cite;
}
var html = '<span class="morecontent">' + content + '</span>' + moretext + cite_link + '<br />';
$(this).replaceWith(html);
}
if (i+1 === quote_count) // this will be executed at the end of the loop
{
// deal with being linked to a comment, so we can put the window to the correct scroll position, since it will be different due to hidden quotes making the page smaller
if(window.location.hash)
{
var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
if (hash.indexOf("r") >= 0)
{
$('#'+hash)[0].scrollIntoView();
}
}
}
});
}
The problem is that when I reload ".comments" through ajax/load the above function no longer works:
function paginate_comments(page, article_id)
{
var url = "/includes/ajax/post_comment.php";
var current_url = window.location.href;
var host = window.location.host;
if(current_url.indexOf(host + '/admin.php?module=reviewqueue') != -1 || current_url.indexOf(host + '/admin.php?module=articles&view=Submitted') != -1 || current_url.indexOf(host + '/admin.php?module=articles&view=Submitted') != -1)
{
var area = 'admin';
}
else
{
var area = 'normal';
}
$('.comments').load(url, {'type':'reload', 'article_id': article_id, 'page': page, 'area': area}, function()
{
$(".lb-container").show();
$('.box.comments').get(0).scrollIntoView();
hide_long_quotes();
});
}
Not sure why it doesn't work, as the function is being called in the completed callback part of the load function?
What about giving the element collection to that function:
function hide_long_quotes(var comments = false)
{ /* for the case that you don't pass a collection to the function, maybe in the first call when the page is loaded */
comments = comments ? comments : $('.comments .comment_quote');
comments.each(function(i)
{
...
}
function paginate_comments(page, article_id)
{
...
$('.comments').load(
url,
{
'type':'reload',
'article_id': article_id,
'page': page,
'area': area
},
function()
{
$(".lb-container").show();
$('.box.comments').get(0).scrollIntoView();
hide_long_quotes($('.comments .comment_quote'));
}
);
}

Jquery hover effects stop working after ajax call

In my website there are some ajax calls that filter product results. There are some effects applied on these products, which stop working after ajax call completes.
At the bottom of the page's code, there's the following:
jQuery(function($) {
jQuery('.category-products-grid').on('mouseenter', '.item', function() {
...
...
...
}).on('mouseleave', '.item', function() {
...
...
...
});
});
I've seen lots of similar posts about this issue, but none of the solutions suggested worked for me.
UPDATE
Here is the ajax call code. i didn't posted before because I don't believe it provides helpful information. There are many functions called int it and the code is too big to post here. The function that matters here is replaceProductsBlock(), and so I'll post it here:
var request = new Ajax.Request(url,
{
method:'GET',
parameters:params,
onSuccess: function(transport){
....
replaceProductsBlock(response);
....
},
onFailure: function(){
....
}
});
replaceProductsBlock: function(response, need_scroll){
var content = response.product_list;
if (typeof(this.gan_static_navigation_url) != 'undefined' && this.gan_static_navigation_url){
if ($$('div.col-main').length > 0){
var col_main = $$('div.col-main')[0];
col_main.innerHTML += '<div class="category-view">' + content + '</div>';
}
return;
}
var replace_toolbar = false;
if($$('div.category-products').length > 0){
element = $$('div.category-products')[0];
if (element.select('div.toolbar').length == 0){
replace_toolbar = true;
}
}else if($$('div.col-main p.note-msg').length > 0){
element = $$('div.col-main p.note-msg')[0];
}else{
return;
}
if (content && content.toElement){
content = content.toElement();
}else if (!Object.isElement(content)) {
content = Object.toHTML(content);
var tempElement = document.createElement('div');
content.evalScripts.bind(content).defer();
content = content.stripScripts();
tempElement.innerHTML = content;
el = this.getElementsByClassName('category-products', tempElement);
if (el.length > 0){
content = el[0];
}else{
el = this.getElementsByClassName('note-msg', tempElement);
if (el.length > 0){
content = el[0];
if (this.gan_shop_by_area == 1){
var shop_by_content = Object.toHTML(response.navigation);
shop_by_content.evalScripts.bind(shop_by_content).defer();
shop_by_content = shop_by_content.stripScripts();
var tempElement = document.createElement('div');
tempElement.innerHTML = shop_by_content;
var shop_by = this.getElementsByClassName('block-layered-nav', tempElement);
if (shop_by.length > 0)
{
shop_by = shop_by[0];
shop_by.id = 'gan_tmp_shop_by';
new Insertion.Before(element, shop_by);
}
}
}else{
return;
}
}
}
element.parentNode.replaceChild(content, element);
if (replace_toolbar && $$('div.category-products').length > 0){
this.ganReplaceToolbal(response.product_list);
}
if (typeof(need_scroll) != 'undefined' && need_scroll){
if ($$('div.category-products').length > 0){
var category_products = $$('div.category-products')[0];
category_products.scrollTo();
}
}
},
After testing and failing again and again to solve this (used jquery live(), one(), livequery() and many many more..) I finally found a solution.
It's described in this article:
Re-binding jQuery Events on AJAX Callbacks
The code I used looks something like this:
function initBinding(){
jQuery('.category-products-grid > .item').hover(function() {
...
...
}, function() {
...
...
});
}
var request = new Ajax.Request(url,
{
...
...
onSuccess: function(transport){
initBinding();
}
});

Javascript file "FASW transitions" duplicating my header info. How to fix

Ok! I'm working on a wordpress site, and everything this javascript add on is supposed to do, it does...But, when I inspect element via safari develop, I notice that it's loading all of my headers scripts,meta,styles etc. into the body as well as the head. I can't figure out why. Here's what the script looks like:
function ft(params) {
var ol= document.addEventListener?"DOMContentLoaded":"load"; //on load event
var navB = params.navB || "reverse slide"; //backbrowser button effect, default empty
var but = params.but || false; //Allow transitions on input type button
var cBa = params.cBa || function() {};
function aDL(url, t, o) { //Ajax Div Load
if (window.XMLHttpRequest) {
r = new XMLHttpRequest();
} else if (window.ActiveXObject) {
r = new ActiveXObject("Microsoft.XMLHTTP");
}
if (r != undefined) {
r.onreadystatechange = function() {Ol(r, t, o);};
r.open("GET", url, true);
r.send("");
}
}
function Ol(r, t, o) { //On load div
if (r.readyState == 4) {
if (r.status == 200 || r.status == 0) {
t.innerHTML = r.responseText;
o();
} else {
t.innerHTML="Error:\n"+ r.status + "\n" +r.statusText;
}
}
}
function DE() //Div Effect
{
var dochtml = document.body.innerHTML;
document.body.innerHTML = "";
var d1 = document.createElement("div");
d1.id = "d1";
d1.style.zIndex = 2;
d1.style.position = "absolute";
d1.style.width = "100%";
d1.style.height = "100%";
d1.style.left = "0px";
d1.style.top = "0px";
document.body.appendChild(d1);
d1.innerHTML = dochtml;
var d2 = document.createElement("div");
d2.id = "d2";
d2.style.zIndex = 1;
d2.style.position = "absolute";
d2.style.width = "100%";
d2.style.height = "100%";
d2.style.left = "0px";
d2.style.top = "0px";
document.body.appendChild(d2);
return {d1: d1, d2: d2 };
}
function timeOuts(e, d1,d2)
{
setTimeout(function() { d1.className = e + " out"; }, 1);
setTimeout(function() { d2.className = e + " in"; }, 1);
setTimeout(function() {
document.body.innerHTML = d2.innerHTML;
cBa();
}, 706);
}
function slideTo(href, effect, pushstate)
{
var d = DE();
var d1 = d.d1;
var d2 = d.d2;
aDL(href, d2,
function() {
if (pushstate && window.history.pushState) window.history.pushState("", "", href);
timeOuts(effect,d1,d2);
}
);
}
function dC(e){ //Detect click event
var o;
var o=e.srcElement || e.target;
var tn = o.tagName.toLowerCase();
if (!but || tn!="input" || o.getAttribute("type")!="button") //if it is not a button
{
//try to find an anchor parent
while (tn!=="a" && tn!=="body")
{
o = o.parentNode;
tn = o.tagName.toLowerCase();
}
if (tn==="body") return;
}
var t = o.getAttribute("data-ftrans");
if (t)
{
e.preventDefault();
var hr = o.getAttribute("href") || o.getAttribute("data-href");
if (hr) slideTo(hr, t, true);
}
}
function aE(ev, el, f) { //Add event
if (el.addEventListener) // W3C DOM
el.addEventListener(ev,f,false);
else if (el.attachEvent) { // IE DOM
var r = el.attachEvent("on"+ev, f);
return r;
}
}
aE("click", window, dC);
aE(ol, document, //On load
function(ev)
{
aE("popstate", window, function(e) { //function to reload when back button is clicked
slideTo(location.pathname, navB, false);
});
}
);
}
here is the link to the site: http://www.fasw.ws/faswwp/non-jquery-page-transitions-lightweight/
I assume that thats not supposed to happen. So im trying to figure out how to keep it clean, and keep the head files loaded in the head, and only load the page content. I cannot figure this one out, some help from the pros is needed :)
FASW comes with two functions that serves as "hooks" both before and after initializing the component. you can do it like this:
(function inittrans()
{
initComponents();
var params = { /*put your options here*/ };
new ft(params);
})();
function onTransitionFinished()
{
initComponents();
}
function initComponents() {
// here is where you put your "other" javascript codes
}
Notice how your javascript codes are executed after loading your initial page and once again after the transition happened. Anyway, this is how I got the work around on it 'coz javascript codes just won't work as they are loaded by FASW via Ajax on-the-fly.

caret positionning in contentEditable containing dom images

I'm having problems with setting caret position in a contentEditable iframe, as soon as I add an ":)" emoticon.
How would you manage?
Here is a basic template:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var init = function () { // initialization
this.editor = $('#wysiwyg');
this.editor.curWin = this.editor.prop('contentWindow');
this.editor.curDoc = this.editor.curWin.document;
this.editor.curDoc.designMode = "On";
this.editor.curBody = $(this.curDoc).contents().find('body');
this.editor.html = function (data) { // shortcut to set innerHTML
if (typeof data == "undefined")
return this.curBody.html();
this.curBody.html(data);
return $(this);
};
var emoji = function (data) { // replace every :) by an image
return data.replace(':)', '<img src="http:\/\/dean.resplace.net\/blog\/wp-content\/uploads\/2011\/10\/wlEmoticon-smile1.png"\/>');
};
var self = this;
this.editor.contents().find('body').keypress(function (ev) { // handler on key pressed
var me = $(this);
setTimeout(function () { // timeout so that the iframe is containing the last character inputed
var sel = self.editor.curWin.getSelection();
var offset = sel.focusOffset;
me.html( emoji( me.html() ) );
var body = $(self.editor.curDoc).find('body').get(0);
sel.collapse(body, offset); //here is where i set positionning
return;
}, 100);
return true;
});
};
</script>
</head>
<body onload="init()">
<iframe id="wysiwyg"></iframe>
</body>
</html>
StackOverflow demands that i add more context to explain the code sections, but for me it seems to be clear. So sorry to add so more "cool story bro" comments but i can't see what i can explain more than this. Anyway, i'm open to any question.
Quick fix...
check to see if a replacement is being made... if there is one being made then readjust the caret. otherwise leave it be.
var init = function() { // initialization
this.editor = $('#wysiwyg');
this.editor.curWin = this.editor.prop('contentWindow');
this.editor.curDoc = this.editor.curWin.document;
this.editor.curDoc.designMode = "On";
this.editor.curBody = $(this.curDoc).contents().find('body');
this.editor.html = function(data) { // shortcut to set innerHTML
if (typeof data == "undefined") return this.curBody.html();
this.curBody.html(data);
return $(this);
};
var emoji = function(data) { // replace every :) by an image
var tmp = data;
tmp = tmp.replace(':)', '<img src="http:\/\/dean.resplace.net\/blog\/wp-content\/uploads\/2011\/10\/wlEmoticon-smile1.png"\/>');
if (tmp !== data) {
return [true, tmp];
}
return [false, tmp];
};
var self = this;
this.editor.contents().find('body').keypress(function(ev) { // handler on key pressed
var me = $(this);
var res = emoji(me.html());
if (res[0]) {
setTimeout(function() { // timeout so that the iframe is containing the last character inputed
var sel = self.editor.curWin.getSelection();
var offset = sel.focusOffset;
me.html(res[1]);
var body = $(self.editor.curDoc).find('body').get(0);
sel.collapse(body, offset); //here is where i set positionning
return;
}, 100);
}
return true;
});
};
init();​

"$.______ is not a function" error. What is wrong?

I'm trying to add an image rotator to my site but for some reason firebug tells me the function I need to call to start the rotator isn't defined. My jQuery file is loading just fine and the image rotator script is loading so I'm not sure what is wrong. The site is heritage.newcoastmedia.com but I'll go ahead and post the script:
;(function($) {
$.fn.featureList = function(options) {
var tabs = $(this);
var output = $(options.output);
new jQuery.featureList(tabs, output, options);
return this;
};
$.featureList = function(tabs, output, options) {
function slide(nr) {
if (typeof nr == "undefined") {
nr = visible_item + 1;
nr = nr >= total_items ? 0 : nr;
}
tabs.removeClass('current').filter(":eq(" + nr + ")").addClass('current');
output.stop(true, true).filter(":visible").fadeOut();
output.filter(":eq(" + nr + ")").fadeIn(function() {
visible_item = nr;
});
}
var options = options || {};
var total_items = tabs.length;
var visible_item = options.start_item || 0;
options.pause_on_hover = options.pause_on_hover || true;
options.transition_interval = options.transition_interval || 5000;
output.hide().eq( visible_item ).show();
tabs.eq( visible_item ).addClass('current');
tabs.click(function() {
if ($(this).hasClass('current')) {
return false;
}
slide( tabs.index( this) );
});
if (options.transition_interval > 0) {
var timer = setInterval(function () {
slide();
}, options.transition_interval);
if (options.pause_on_hover) {
tabs.mouseenter(function() {
clearInterval( timer );
}).mouseleave(function() {
clearInterval( timer );
timer = setInterval(function () {
slide();
}, options.transition_interval);
});
}
}
};
});
And here is the script to start the image rotator:
<script language="javascript">
$(document).ready(function() {
$.featureList(
$("#tabs li a"),
$("#output li"), {
start_item : 1
}
);
});
</script>
Your code creates an anonymous function, but doesn't call it.
You need to call the function by adding (jQuery) at the end.
You cannot do $.featureList(
See Chrome error:
The plugin needs to applied to an object
You've just slightly missed out on the right syntax for creating a plugin. What you really want is:
(function($) {
$.fn.featureList = function() { // etc; }
$.featureList = function() { // yet more etc; }
})(jQuery);

Categories

Resources