jQuery document.ready not working - javascript

I've been working on this for a couple of days now and have been unable to find a solution. Basically, I have to JS scripts in my head that won't execute the $(document).ready(...). The strange thing is that I have other scripts that work with it just fine. Here are the two I am having problems with: (I've added a couple comments about what I have tried)
<% content_for(:head) do %>
<script type="text/javascript">
$(document).ready(function() {
$('.button-print-ticket').click(function(e) {
e.preventDefault();
var header = $('.social-header');
header.queue(function() {
var search_string ='#map-canvas img[src=https://maps.gstatic.com/mapfiles/google_white.png]';
var glink = $(search_string).parent().parent();
glink.replaceWith(glink.html());
$(this).dequeue();
});
header.hide();
header.queue(function() {
window.print();
$(this).dequeue();
});
header.queue(function() {
$('.social-header').show();
$(search_string).parent().replaceWith(glink);
$(this).dequeue();
});
});
});
</script>
<script type="text/javascript">
//an alert here works
if(screen.width >= 800) {
//an alert here works too
$(document).ready(function() {
//an alert here only works in the console
$(document).ready(function(){
$('#overlay').fadeIn('fast',function(){
$('#box').animate({'top':'160px'},500);
});
});
$('#boxclose, #bt-fbshare, #bt-tweet, #bt-email').click(function(){
$('#box').hide("drop", { direction: "up" }, 100, function(){
$('#overlay').fadeOut('fast');
});
});
$(document).keyup(function(e) {
if (e.keyCode == 27){
$('#box').hide("drop", { direction: "up" }, 100, function(){
$('#overlay').fadeOut('fast');
});
}
});
});
}
</script>
<% end %>
I also included the Ruby On Rails tag because it is the only difference that I can discern. (The JS IS shown in Firebug) I don't have an onload in my <body> tag either. Another oddity is that it used to work and I don't recall making any changes to either of these scripts.
Edit 2:
One other thing: I can also put console.log($) just before if (screen-width >= 800) and it tells me that $ is a function.
Edit:
Here is the generated HTML:
<head>
<style type="text/css">#media print { .gmnoprint { display:none }}#media screen { .gmnoscreen { display:none }}</style>
<title>Web Page</title>
<meta content="text/html;charset=UTF-8" http-equiv="content-type"/>
<meta content="ALL" name="robots"/>
<meta content="5 Days" name="revisit-after"/>
<meta content="EN" name="language"/>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale = 1.0, maximum-scale = 1.0"/>
<link type="text/css" rel="stylesheet" media="screen, projection, print" href="/stylesheets/screen.css?1347374478"/>
<link type="text/css" rel="stylesheet" media="screen, projection, print" href="/stylesheets/global.css?1346943598"/>
<link type="text/css" rel="stylesheet" media="print" href="/stylesheets/print.css?1343928684"/>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--[if lte IE 7]><link href="/stylesheets/ie7.css?1343928684" media="screen, projection" rel="stylesheet" type="text/css" /><![endif]-->
<!--[if !IE]><link href="/stylesheets/media.css?1343928684" media="screen, projection" rel="stylesheet" type="text/css" /><![endif]-->
<script type="text/javascript" src="/javascripts/jquery.min.js?1343928684"></script>
<script type="text/javascript" src="/javascripts/jquery.ui.min.js?1343928684"></script>
<script type="text/javascript" src="/javascripts/jquery.ajax-submit.js?1343928684"></script>
<script type="text/javascript" src="/javascripts/modernizr-2.js?1343928684"></script>
<script type="text/javascript" src="/javascripts/date.format.js?1343928684"></script>
<script type="text/javascript" src="/javascripts/geo.js?1343928684"></script>
<script type="text/javascript" src="/javascripts/spin.min.js?1343928684"></script><style></style>
<script type="text/javascript" src="/javascripts/application.js?1347326686"></script>
<script type="text/javascript" src="/javascripts/global.js?1345692570"></script>
<script type="text/javascript">
var logged_in = true;
$(function() {
if (logged_in) {
$('.signed-in').show();
$('.signed-out').hide();
} else {
$('.signed-in').hide();
$('.signed-out').show();
}
$('.sign-out-link').click(function(e) {
e.preventDefault();
$('.signed-in').hide();
$('.signed-out').show();
logged_in = false;e
window.location='/customers/destroy_session';
});
});
</script>
<!--<script type="text/javascript">
document.write(unescape("%3Cscript src='" + ((document.location.protocol=="https:")?"https://snapabug.appspot.com":"http://www.snapengage.com") + "/snapabug.js' type='text/javascript'%3E%3C/script%3E"));</script><script type="text/javascript">
SnapABug.addButton("--------","0","55%");
</script>-->
<style type="text/css">
#map-canvas { width : 100%; height: 100%; }
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=true" type="text/javascript"></script><script type="text/javascript" src="https://maps.gstatic.com/intl/en_us/mapfiles/api-3/9/14/main.js"></script>
<script src="/javascripts/google.maps.styled-marker.js" type="text/javascript"></script>
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var venueMarker = new google.maps.Marker;
var pu_map;
var map;
$(function() {
var latlng = new google.maps.LatLng(40.256676, -111.644755);
var mapOptions = {
zoom : 13,
center : latlng,
mapTypeId : google.maps.MapTypeId.ROADMAP,
disableDefaultUI : true,
zoomControl : true
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
new google.maps.Marker({
position : latlng,
map : map
});
});
$(function() {
directionsDisplay = new google.maps.DirectionsRenderer();
var latlng = new google.maps.LatLng(40.256676, -111.644755);
var mapOptions = {
zoom : 13,
center : latlng,
mapTypeId : google.maps.MapTypeId.ROADMAP,
disableDefaultUI : true,
zoomControl : true
};
pu_map = new google.maps.Map(document.getElementById("popup_map_cont"), mapOptions);
directionsDisplay.setMap(pu_map);
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$('.button-print-ticket').click(function(e) {
e.preventDefault();
var header = $('.social-header');
header.queue(function() {
var search_string ='#map-canvas img[src=https://maps.gstatic.com/mapfiles/google_white.png]';
var glink = $(search_string).parent().parent();
glink.replaceWith(glink.html());
$(this).dequeue();
});
header.hide();
header.queue(function() {
window.print();
$(this).dequeue();
});
header.queue(function() {
$('.social-header').show();
$(search_string).parent().replaceWith(glink);
$(this).dequeue();
});
});
});
</script>
<script type="text/javascript">
if(screen.width >= 800) {
$(document).ready(function() {
$(document).ready(function(){
$('#overlay').fadeIn('fast',function(){
$('#box').animate({'top':'160px'},500);
});
});
$('#boxclose, #bt-fbshare, #bt-tweet, #bt-email').click(function(){
$('#box').hide("drop", { direction: "up" }, 100, function(){
$('#overlay').fadeOut('fast');
});
});
$(document).keyup(function(e) {
if (e.keyCode == 27){
$('#box').hide("drop", { direction: "up" }, 100, function(){
$('#overlay').fadeOut('fast');
});
}
});
});
}
</script>
<script type="text/javascript" charset="UTF-8" src="https://maps.gstatic.com/cat_js/intl/en_us/mapfiles/api-3/9/14/%7Bcommon,util,marker%7D.js"></script><script type="text/javascript" charset="UTF-8" src="https://maps.gstatic.com/cat_js/intl/en_us/mapfiles/api-3/9/14/%7Bmap%7D.js"></script><script type="text/javascript" charset="UTF-8" src="https://maps.gstatic.com/cat_js/intl/en_us/mapfiles/api-3/9/14/%7Bonion%7D.js"></script><script type="text/javascript" charset="UTF-8" src="https://maps.gstatic.com/cat_js/intl/en_us/mapfiles/api-3/9/14/%7Bcontrols%7D.js"></script><script type="text/javascript" charset="UTF-8" src="https://maps.gstatic.com/cat_js/intl/en_us/mapfiles/api-3/9/14/%7Bstats%7D.js"></script><script async="true" type="text/javascript" src="http://a.adroll.com/j/roundtrip.js"></script>

Maybe you should try putting all your JS code in the same tag script and $(document).ready() function
<% content_for(:head) do %>
<script type="text/javascript">
$(document).ready(function() {
$('.button-print-ticket').click(function(e) {
e.preventDefault();
var header = $('.social-header');
header.queue(function() {
var search_string ='#map-canvas img[src=https://maps.gstatic.com/mapfiles/google_white.png]';
var glink = $(search_string).parent().parent();
glink.replaceWith(glink.html());
$(this).dequeue();
});
header.hide();
header.queue(function() {
window.print();
$(this).dequeue();
});
header.queue(function() {
$('.social-header').show();
$(search_string).parent().replaceWith(glink);
$(this).dequeue();
});
});
if(screen.width >= 800) {
$('#overlay').fadeIn('fast',function(){
$('#box').animate({'top':'160px'},500);
});
$('#boxclose, #bt-fbshare, #bt-tweet, #bt-email').click(function(){
$('#box').hide("drop", { direction: "up" }, 100, function(){
$('#overlay').fadeOut('fast');
});
});
$(document).keyup(function(e) {
if (e.keyCode == 27){
$('#box').hide("drop", { direction: "up" }, 100, function(){
$('#overlay').fadeOut('fast');
});
}
});
}
});
</script>
<% end %>
And as marteljn comments, be sure to reference JQuery in the head section
<script type="text/javascript" src="jquery.js"></script>
If it's still not working you can post the generetad HTML as proposed by jfriend00.

Related

API problems with jQuery

I am trying to implement an API into my web page. However, for some reason none of the data is being displayed. I did a similar thing as I did with a previous API and it isn't working.
The following is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script language="JavaScript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script language="JavaScript" type="text/javascript">
$(function () {
var req = $.ajax({
url: "http://api.lmiforall.org.uk/api/v1/soc/search?q=computer"
});
console.log(data);
req.done(function (data) {
var wrapperDiv = $("<div />", {
"class": "wrapper"
});
var title = $("<h2 />", {
text: data[0].title
});
wrapperDiv.append(title);
$("body").append(wrapperDiv);
});
});
</script>
</body>
</html>
With the API is datatype for title, which is a job title, and I am trying to display the first title on the page. However, nothing is displayed and I get these error messages:
I honestly have no clue what is wrong with this. Any help would be much appreciated.
You log "data" outside of "done" method scope. try like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script language="JavaScript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script language="JavaScript" type="text/javascript">
$(function () {
var req = $.ajax({
url: "http://api.lmiforall.org.uk/api/v1/soc/search?q=computer"
});
req.done(function (data) {
console.log(data);
var wrapperDiv = $("<div />", {
"class": "wrapper"
});
var title = $("<h2 />", {
text: data[0].title
});
wrapperDiv.append(title);
$("body").append(wrapperDiv);
});
});
</script>
</body>
</html>

When I Replace Remote File with Local File Console Error - Skulpt

I am making a Python editor in HTML and JavaScript, with CodeMirror for code indentation, line numbering and syntax coloring, and Skulpt for the execution.
I have some code that had an external script referenced in it (http://www.skulpt.org/static/skulpt.min.js):
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript">
</script>
<script src="http://www.skulpt.org/static/skulpt.min.js" type="text/javascript">
</script>
<script src="skulpt-stdlib.js" type="text/javascript">
</script>
<script src="codemirror.js" type="text/javascript">
</script>
<script src="python.js" type="text/javascript">
</script>
<link href="codemirror.css" rel="stylesheet" type="text/css">
<title></title>
</head>
<body>
<script type="text/javascript">
var editor;
function outf(text) {
var mypre = document.getElementById("dynamicframe");
mypre.innerHTML = mypre.innerHTML + text;
}
function builtinRead(x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
}
function runit() {
var prog = editor.getDoc().getValue();
var mypre = document.getElementById("dynamicframe");
mypre.innerHTML = '';
Sk.pre = "dynamicframe";
Sk.configure({
output: outf,
read: builtinRead
});
(Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = 'canvas';
var myPromise = Sk.misceval.asyncToPromise(function() {
return Sk.importMainWithBody("<stdin>", false, prog, true);
});
myPromise.then(function(mod) {
console.log('success');
},
function(err) {
console.log(err.toString());
});
}
//<![CDATA[
window.onload = function() {
editor = CodeMirror.fromTextArea(document.getElementById('textbox'), {
mode: {
name: "python",
version: 2,
singleLineStringErrors: false
},
lineNumbers: true,
indentUnit: 4
});
} //]]>
</script>
<textarea id="textbox" name="textbox"></textarea>
<br>
<button onclick="runit()" type="button">Run</button>
<pre id="dynamicframe"></pre>
<div id="canvas"></div>
</body>
</html>
I want all the scripts stored locally (excluding jQuery), so I copied over http://www.skulpt.org/static/skulpt.min.js to the local server and called it skulpt.min.js. I then changed the line:
<script src="http://www.skulpt.org/static/skulpt.min.js" type="text/javascript">
</script>
to...
<script src="skulpt.min.js" type="text/javascript">
</script>
and now the code is bringing up this error in the console:
Uncaught ReferenceError: Sk is not defined
on line 38 of the HTML:
Sk.pre = "dynamicframe";
Why is this happening and how can I fix it?

Phonegap build Geolocation not working

js: i use simple alert to display the location, and use phonegap build to compile. Device ready alert is shown! But not any other alerts!
document.addEventListener("deviceready", getDeviceLocation , false);
function getDeviceLocation () {
alert('device ready');
navigator.geolocation.getCurrentPosition(showPosition, showError, { enableHighAccuracy: true } );
}
function showPosition(position) {
alert('show postion called');
alert("Latitude: " + position.coords.latitude +
"Longitude: " + position.coords.longitude);
}
function showError(error) {
alert('show error called');
alert("Errorcode: " + error.code +
"Errormessage: "+ error.message );
}
html:the html page is as follows:
<!DOCTYPE html>
<html ng-app>
<head>
<link rel="stylesheet" href="style.css">
<!--<link rel="stylesheet" href="bootstrap.css">-->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="bootstrap.css">
<!-- Latest compiled and minified JavaScript -->
<script src="angular.min.js"></script>
<script src="cordova.js"></script>
<script src="angular.animate.min.js"></script>
<script src="angular.route.min.js"></script>
<link rel="stylesheet" href="font-awesome.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
</body>
<script type="text/javascript" src="pro.js"></script>
<script type="text/javascript" src="bootstrap.js"></script>
<script type="text/javascript" src="script.js"></script>
</html>
This code works for me. Hope will help you.
newMapForGuest: function()
{
// setting here default latitude and longitude in case geolocation does not work.
var defaultLatLng = new google.maps.LatLng(1.290, 103.851);
if ( navigator.geolocation )
{
function success(pos) // function will call on success
{
alert('Latitude: '+ pos.coords.latitude +' Longitude: '+pos.coords.longitude);
}
function fail(error) // function will call on fail
{
alert('error message: ' +error);
}
// intializing geolocation to get current position
navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 10000});
}
else
{
// in case geolocation does not work then call code mentioned here.
}
},

Change my redirect code

Below is my Geo Redirect Code that needs change,**What I would like is to add a meta redirect if possible so an eg would be:-
<html>
<head>
<title>GEO Redirect- Working Demo</title>
<!-- GEO Redirect -->
<script type="application/javascript">
function getgeoip(json){
if(json.country_code == "US"){
window.location = "http://msn.com/"
<!-- Can the above line be replaced to: <META HTTP-EQUIV='Refresh' CONTENT='0; URL=msn.com'> -->
} else {
window.location = "http://google.com/"
<!-- Can the above line be replaced to: <META HTTP-EQUIV='Refresh' CONTENT='0; URL=google.com'> -->
}
}
</script>
<script type="application/javascript" src="http://www.telize.com/geoip?callback=getgeoip"></script>
</head>
</html>
Guys any help would be highly appreciated, thanks again.
If using jquery;
$('head').append('<META HTTP-EQUIV="Refresh" CONTENT="0; URL=msn.com">');
or javascript:
var meta = document.createElement('meta');
meta.httpEquiv = "Refresh";
meta.content = "0; URL=msn.com";
document.getElementsByTagName('head')[0].appendChild(meta);
However, the rendering mode is fixed when the page is loaded, so this will most probably not work as you want it to...
If you're trying to redirect after some time, then you could do this:
<html>
<head>
<title>GEO Redirect- Working Demo</title>
<!-- GEO Redirect -->
<script type="application/javascript">
function getgeoip(json){
if(json.country_code == "US"){
// will redirect to this page, but only after 2 secs.
setTimeout(function () { window.location.href = "http://msn.com/"; }, 2000);
} else {
// will redirect to this page, but only after 2 secs.
setTimeout(function () { window.location.href = "http://google.com/"; }, 2000);
}
}
</script>
<script type="application/javascript" src="http://www.telize.com/geoip?callback=getgeoip"></script>
</head>
</html>

Javascript stops running with no error message

Using an Uploadify and JGrowl combo:
<link rel="stylesheet" type="text/css" href="css/default.css" /><link rel="stylesheet" type="text/css" href="css/jgrowl.css" />
<script type="text/javascript" src="js/jquery1.4.4.js"></script>
<script type="text/javascript" src="js/jgrowl.js"></script>
<link rel="stylesheet" type="text/css" href="css/artworkDesigner.css" />
<link href="js/uploadify-2.1.4/uploadify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="js/uploadify-2.1.4/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/uploadify-2.1.4/swfobject.js"></script>
<script type="text/javascript" src="js/uploadify-2.1.4/jquery.uploadify.v2.1.4.min.js">/script>
<script type="text/javascript">
// <![CDATA[
var uploadType = "art";
var templateID = "42scs";
$(document).ready(function() {
$('#fileInput').uploadify({
'uploader': 'js/uploadify-2.1.4/uploadify.swf',
'script': 'js/uploadify-2.1.4/UploadHandler.ashx',
'cancelImg': 'js/uploadify-2.1.4/cancel.png',
'scriptData': { 'type': uploadType, 'templateID': templateID },
'auto': true,
'multi': true,
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.png;*.gif;*.bmp;*.jpeg',
'queueSizeLimit': 90,
'sizeLimit': 4000000,
'buttonText': 'Choose Images',
'folder': '/uploads/test',
'onComplete': function(event, ID, fileObj, response, data) {
if (response != "1") {
alert(response); // ALERTS 'ERROR TEXT' which is expected
// DOESNT RUN THIS LINE:, AND REST OF SCRIPT SEEMS TO FREEZE
$.jGrowl("<strong>Error!</strong><br />" + response, { sticky: true });
alert("flag"); // THIS IS NOT RUNNING
} else {
alert(fileObj.name + "\n" + fileObj.filePath + "\n" + ID + "\n");
alert(response);
}
}
});
});
// ]]></script>
This script works fine, when templateID is set to a real number (without a string at the end to purposefully throw an error), but when an invalid string is passed in 42scs as shown in the code above, the script alerts
"Some error text"
Which is the correct return value when an exception is thrown server side. Then the script just stops doing anything else, when it is meant to throw the Jgrowl error. Any ideas why this isn't happening?
I'm using Jgrowl exactly the same on another page and it works fine.
Double reference to Jquery library will conflict:
<script type="text/javascript" src="js/jquery1.4.4.js"></script>
<script type="text/javascript" src="js/uploadify-2.1.4/jquery-1.4.2.min.js"></script>

Categories