included .js file preventing jQuery from loading - javascript

I am new to jquery/web design and download a template to try and familiarize myself. I am having an issue with a certain script that is preventing my jQuery from loading. I have this in the header on my site:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="layout/scripts/jquery-mobilemenu.min.js"></script>
<script type="text/javascript" src="layout/scripts/responsiveslides.js-v1.53/responsiveslides.min.js"></script>
<script src="layout/scripts/custom.js"></script>
The culprit file is the <script type="text/javascript" src="layout/scripts/jquery-mobilemenu.min.js"></script>; everytime I disable this line jQuery works fine. I am really not sure what to identify in the file that would cause jQuery to not load. The contents of js:
jQuery.noConflict()(function ($) {
// Create the dropdown base
$("<form id='mobilemenu'><select /></form>").appendTo("#topnav");
// Create default option "Go to..."
$("<option />", {
"selected": "selected",
"value": "",
"text": "Click For Menu"
}).appendTo("#topnav select");
//Populate dropdown with menu items
$("#topnav a").each(function () {
var el = $(this);
var prefix = '';
switch (el.parents().length) {
case (6):
prefix = '';
break;
case (8):
prefix = '- - - ';
break;
case (10):
prefix = '- - - - - ';
break;
case (12):
prefix = '- - - - - - - ';
break;
default:
prefix = '';
break;
}
$("<option />", {
"value": el.attr("href"),
"text": prefix + el.text()
}).appendTo("#topnav select");
$("#topnav select").change(function () {
window.location = $(this).find("option:selected").val();
});
});
});
Would anyone be able to point me in the right direction with correcting this file? I have tried to move the order that my scripts load and it doesn't matter the order, jQuery doesn't load when the mobilemenu script is included.

Within the script you mention as causing the problem you will see a call to noConflict() this method allows jQuery to be used with other libraries that also rely on the $ as an entry point by removing $ as an alias to jQuery.
Immediately following the noConflict() call you see a very specific function signature that is being passed to jQuery:
(function ($) {
//function code here
});
jQuery is going to call this function and when it does it will pass itself in as the $ parameter and within the scope of that function you now access jQuery using $ again.
So with the script the way it is you will need to use jQuery by name.
Have a look at the documentation on noConflict for more details.
There are also several other questions on SO with regards to noConflict, this one might help in particular.

Related

Use inline javascript to set some values [duplicate]

I'm wondering if there is a way to get a handle on the DOM element that contains the script inside it. So if I had:
<script type="text/javascript> var x = ?; </script>
Is there a way that I can assign "x" a reference to the script element that contains "x"?
There isn't a truly safe way.
The closest you can come is to use getElementsByTagName to get all the scripts, get its length, get the last script element, then work from there.
This can fail if the script is deferred or if the script has been dynamically added to the page before another script element.
You could include some marker text in the script element, and then (similar to what David said), you can loop through all the script elements in the DOM (using getElementsByTagName or whatever features your library, if you're using one, may have). That should find the element reliably. That would look something like this (live example):
<body>
<script id='first' type='text/javascript'>
(function() {
var x = "MARKER:first";
})();
</script>
<script id='second' type='text/javascript'>
(function() {
var x = "MARKER:second";
})();
</script>
<script id='third' type='text/javascript'>
(function() {
var x = "MARKER:third";
})();
</script>
<script id='last' type='text/javascript'>
(function() {
var scripts, index, script;
scripts = document.getElementsByTagName("script");
for (index = 0; index < scripts.length; ++index) {
script = scripts[index];
if (script.innerHTML.indexOf("MARKER:second") >= 0
&& script.id !== "last") {
display("Found MARKER:second in script tag #" + script.id);
}
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
})();
</script>
</body>
Note that, like the script above, if you're looking for a script tag marker from within a different script tag, you'll need to handle that. Above it's handled by checking the ID of the script tag, but you can also just break it up in the one you don't want to find, like this (live example):
if (script.innerHTML.indexOf("MARKER:" + "second") >= 0) {
display("Found MARKER:" + "second in script tag #" + script.id);
}

Google Translate: Callback when a language is selected

I have added the Google Translate plugin to my web page. How can I get a callback to my JavaScript function whenever the user selects a language from the drop down menu that the plugin adds to my web page? The Google Translate API documentation does not seem to have any information on this. I have read through the JavaScript code of the Google Translate plugin and I cannot see anything that is helpful.
It will also be fine if I get a callback to my function just before the translation of my web page begins or just after the translation of my web page ends or just before or after the translation of any specific element in my web page.
Here is the HTML for a simplified version of my web page:
<html>
<head>
</head>
<body>
<!-- Google Website Translator plugin -->
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'es', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<div>
<p>This part can be translated using the Google Translator plugin.</p>
</div>
<script type="text/javascript">
function translationCallback() {
// This function needs to be called when Google translates this web page.
alert("A language was selected from the Google Translator plugin dropdown");
}
</script>
</body>
</html>
Thanks for the responses. Based on the answers and comments in the SO questions referenced in the above responses, I cobbled together the code below which works for me.
I added a hidden div and a listener for its DOMSubtreeModified event. The listener gets called when Google translates the contents of the hidden div. However the listener gets called multiple times for each time a language is selected from the plugin drop down menu. Google seems to be making multiple passes. The original value of the innerHTML seems to be retained as a substring in all the passes except the last. So I check for the original innerHTML substring in the event handler to avoid executing the code multiple times.
Select an initial value for the innerHTML that is distinct for each language in the drop down menu. 'English' works in my case.
<html>
<head>
</head>
<body>
<!-- Google Website Translator plugin -->
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'es', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<div>
<p>This part can be translated using the Google Translator plugin.</p>
</div>
<div id="translationDetector" style="display:none;">English</div>
<script type="text/javascript">
var origValue = document.getElementById("translationDetector").innerHTML;
document.getElementById("translationDetector").addEventListener("DOMSubtreeModified", translationCallback, false);
function translationCallback() {
// This function needs to be called when Google translates this web page.
var currentValue = document.getElementById("translationDetector").innerHTML;
if (currentValue && currentValue.indexOf(origValue) < 0) {
origValue = currentValue;
alert("There is a disturbance in the force: " + currentValue);
}
}
</script>
</body>
</html>
Google translate js uses a cookie to keep track of the current language selection. You could set up a timeout to watch for changes to the cookie.
Here's how I implemented this for Drupal, adaptable to any javascript framework:
Drupal.exampleLanguageChanged = function() {
if (Drupal.exampleGetCookie('googtrans') != cookieValue) {
cookieValue = Drupal.exampleGetCookie('googtrans');
console.log('cookie changed ' + cookieValue);
}
setTimeout(Drupal.exampleLanguageChanged, 500);
};
Drupal.exampleGetCookie = function(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length >= 2) {
return parts.pop().split(";").shift();
}
return '';
};
Drupal.behaviors.exampleSimpleTranslation = {
attach: function(context) {
cookieValue = Drupal.exampleGetCookie('googtrans');
console.log('cookie value ' + cookieValue);
setTimeout(Drupal.exampleLanguageChanged, 500);
}
};
From this SO question, this code apears to work:
var $textfield = find("#google-translate");
var $popup = find("#google_translate_element");
var $select = $popup.find("select");
$textfield.click(function () {
$popup.fadeIn("fast");
return false;
});
$select.bind("change", function () {
$popup.fadeOut("fast");
});
Here's one solution, but I'm not sure if I like it that much. Essentially you check to see if the text or page has changed then when it does you act on that.
Google Translate Widget - Translation complete callback

'$' is undefined error

Trying to use a jQuery plugin and it is not working and this error
'$' is undefined
keeps popping up. I am very new to Javascript and jQuery so please be as simple as possible
<script type="text/javascript" src="wpscripts/jquery-1.4.1.min.js"></script>
<!--[if IE 6]>
<script src="thumb-images/DD_belatedPNG_0.0.8a-min.js"></script>
<script>DD_belatedPNG.fix('#preview_inner div a');</script>
<![endif]-->
<script type="text/javascript">
$(document).ready(function () {
var outer = $("#preview_outer");
var arrow = $("#arrow");
var thumbs = $("#thumbs span");
var preview_pos;
var preview_els = $("#preview_inner div");
var image_width = preview_els.eq(0).width();
thumbs.click(function () {
preview_pos = preview_els.eq(thumbs.index(this)).position();
outer.stop().animate({ 'scrollLeft': preview_pos.left }, 500);
arrow.stop().animate({ 'left': $(this).position().left }, 500);
});
arrow.css({ 'left': thumbs.eq(0).position().left }).show();
outer.animate({ 'scrollLeft': 0 }, 0);
$("#preview_inner").css('width', preview_els.length * image_width);
});
</script>
That usually means that you have to import jquery at the top like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Edit: Here is the link for the updated version. I believe that this page will always update to the latest version of jQuery whereas my above answer won't: HERE
Check your script source path. It's likely not loading in.
If it's at the root of a site use:
<script type="text/javascript" src="/wpscripts/jquery-1.4.1.min.js"></script>
I see you have also tagged ASP.NET, so If it's in a control or somewhere that can be different for each page load, then use the following to have .Net figure out the actual relative path.
<script type="text/javascript" src="<%= ResolveClientUrl("~/wpscripts/jquery-1.4.1.min.js") %>"></script>
I see you are using WordPress.
You often are not able to define links with a relative path.
try using the php function "get_theme_root();" to get the theme root and navigate from there

jQuery is undefined & unexpected token

I have this script that positions a div's background in proportion with the window size:
// JavaScript Document
var jQNC = jQuery.noConflict();
jQNC(document).ready( function () {
setPunchMargin()
jQNC(window).resize( function () {
setPunchMargin();
});
});
function setPunchMargin() {
var windowWidth = jQNC(window).width();
if (windowWidth <= 980) {
var margin = 0;
} else {
var margin = Math.round((windowWidth - 980) / 2);
}
jQNC('.punch').css('background-position', margin + 'px 320px');
}
It works like a charm on my local machine, but when uploading it to the server i get jQuery is undefined and on the jquery library i get unexpected token error.
Can you tell me what is wrong here?
Thank you,
Radu.
You have jQuery included two times;
<script language="javascript" src="http://punchid.com/test/wp-content/themes/punch/js/jquery-1.6.1-min.js" type="text/javascript"></script>
And here;
<script type='text/javascript' src='http://punchid.com/test/wp-includes/js/jquery/jquery.js?ver=1.4.4'></script>
The latter is an older version, I'd suggest removing that one from the code - But double check everything still works correctly afterwards.
This looks like you are not uploading or referencing jQuery correctly. Try using an absolute reference to a Jquery CDN like: http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
(where 1.5.1 is the version of Jquery you'd need).

Manipulate DOM element to extract some nodes and remove others

I need to manipulate HTML code. Specifically, the user should be able to copy/paste the code to create an AddThis button in a textarea, and I want to manipulate the pasted code.
A typical AddThis button looks like this :
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
<a class="addthis_button_tweet"></a>
<a class="addthis_counter addthis_pill_style"></a>
</div>
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-123456798"></script>
<!-- AddThis Button END -->
It consists of start and end comments, a div and/or some links, followed by 2 scripts: a config setting, and a call to their library.
The problem is, we need to call this many times on the page ; so, if I just put this every time I want to place an AddThis button, I fear that at least some browsers will have weird behavior, if it works at all.
So, I want to extract the config setting and the lib call, so I can call them just once, and extract the buttons config, so I can place it as many times as I want on the page.
I have already done that :
var codeAT = $(this).val();
if (codeAT.indexOf("AddThis Button BEGIN") >= 0) {
codeAT = codeAT.replace("<", "<");
codeAT = codeAT.replace(">", ">");
codeAT = $(codeAT);
// extract the call to the config var and the lib
var scriptConfig = "";
var scriptSRC = "";
codeAT.each(function() {
if ($(this).attr("nodeName") == "SCRIPT") {
if ($(this).attr("src") && $(this).attr("src") != "") {
scriptSRC = $(this).attr("src");
} else {
scriptConfig = $(this).text();
}
}
});
// extract the addthis identifier
scriptSRC = scriptSRC.split("=")[1];
}
Now, I can use the vars scriptConfig (with var addthis_config = {"data_track_clickback":true};) and scriptSRC (with ra-123456789), and they have the correct values.
What I want now, is the original code (between the two comments), without the comments, and without the script tags.
To remove the tags, I tried to use codeAT.remove($(this)), but it crashes (something about c.replace not being a function).
To get the code back, I tried codeAT.html(), but it gets only the tags.
Instead of .each() I'd do:
//remove <script> tags and get required info
var scriptSRC = $('script[src]', codeAT).remove().attr('src');
var scriptConfig = $('script:not([src])', codeAT).remove().text();
//get the code (as string)
var code = $('<div>').append(codeAT).remove().html();

Categories