Simple Javascript not working in IE, works in Firefox - javascript

The following is a simple piece of code to have javascript open up a soundcloud audio player in a pop-up window. It works perfectly in firefox and chrome, but doesn't work in IE7; it just shows a blank black screen. Does anyone know why?
I get the yellow drop down that says "to help protect.. IE has restricted this webpage from running scripts or ActiveX controls...." Even when I click on it and say allow, the soundcloud player still doesn't appear.
<HTML>
<HEAD>
<script type='text/javascript'>
function fetchArguments() {
var arg = window.location.href.split("?")[1].split("&"); // arguments
var len = arg.length; // length of arguments
var obj = {}; // object that maps argument id to argument value
var i; // iterator
var arr; // array
for (var i = 0; i < len; i++) {
arr = arg[i].split("="); // split the argument
obj[arr[0]] = arr[1]; // e.g. obj["song"] = "3"
}
return obj;
}
function loadTitle() {
var args = fetchArguments();
document.title = "Audio: Accidential Seabirds - " + args["name"];
}
function loadMusic() {
var args = fetchArguments();
var height = "100";
object = document.createElement("object");
object.height = height;
object.width = "100%";
nameParam = document.createElement("param");
nameParam.name="movie";
nameParam.value ="http://player.soundcloud.com/player.swf?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F" + args["song"];
scriptParam = document.createElement("param");
scriptParam.name="allowscriptaccess";
scriptParam.value="always";
embedTag = document.createElement("embed");
embedTag.allowscriptaccess="always";
embedTag.height= height;
embedTag.src="http://player.soundcloud.com/player.swf?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F" + args["song"];
embedTag.type="application/x-shockwave-flash";
embedTag.width="100%";
object.appendChild(nameParam);
object.appendChild(scriptParam);
object.appendChild(embedTag);
document.getElementsByTagName("body")[0].appendChild(object); // we append the iframe to the document's body
window.innerHeight=100;
window.innerWidth=600;
self.focus();
}
</script>
<script type='text/javascript'>
loadTitle();
</script>
</HEAD>
<BODY bgcolor="#000000" topmargin="0" marginheight="0" leftmargin="0" marginwidth="0">
<center>
<script type='text/javascript'>
loadMusic();
</script>
</center>
</BODY>
</HTML>
The code to call this window might be
function PopupMusic(song, name) {
var ptr = window.open("musicplayer.htm?song="+song+"&name='"+name+"'", song, "resizable='false', HEIGHT=90,WIDTH=600");
if(ptr) ptr.focus();
return false;
}
Listen

I figured it out. You need to use the setAttributeFunction:
function loadVideo() {
var args = fetchArguments();
var videoFrame = document.createElement("iframe");
videoFrame.setAttribute('id', 'videoFrame');
videoFrame.setAttribute('title', 'YouTube video player');
videoFrame.setAttribute('class', 'youtube-player');
videoFrame.setAttribute('type', 'text/html');
videoFrame.setAttribute('width', args["width"]);
videoFrame.setAttribute('height', args["height"]);
videoFrame.setAttribute('src', 'http://www.youtube.com/embed/' + args["vid"]);
videoFrame.setAttribute('frameborder', '0');
videoFrame.allowFullScreen;
document.getElementsByTagName("body")[0].appendChild(videoFrame); // we append the iframe to the document's body
self.focus();
}

Following code works fine in IE/FF/Chrome:
<script type='text/javascript'>
var musicSrc = 'http://player.soundcloud.com/player.swf?url=http%3A%2F%2Fsoundcloud.com%2Frjchevalier%2Fjust-one-day-ft-deni-hlavinka&color=3b5998&auto_play=true&show_artwork=false';
document.write('<object type="application/x-shockwave-flash" width="100%" height="100%" data="'+musicSrc+'"><param name="movie" value="'+musicSrc+'" /></object>');
</script>

Related

Tried writing a do-while loop statement that prints out my statement, but it's not currently printing it

So, I am trying to write a do-while loop statement that prints out the statement of my loop, but my browser isn't printing my text. How can I edit my code to do so?
<!DOCTYPE html>
<html>
<head>
<title>9. Looping Statements in Javascript</title>
</head>
<body>
<h1>9. Looping Statements in Javascript</h1>
<div id="playlist"></div>
<div id="someResult"></div>
<script>
var playlist = [];
playlist[0] = "Willy Wesly";
playlist[1] = "Childish Gambino";
playlist[2] = "Chance The Rapper";
playlist[3] = "Travi$ Scott";
playlist[4] = "Yeezy";
// while
/*
var i = 0;
while (i < playlist.length) {
var element = document.createElement('div');
element.innerHTML = "Now Playing: " + playlist[i];
i++;
document.body.appendChild(element);
}
*/
// do - while
var someResult = false;
do {
var element = document.createElement('div');
element.innerHTML = 'Will print AT LEAST once!';
}
while(someResult);
</script>
</body>
</html>
You need to add the element to the document body.
var someResult = false;
do {
var element = document.createElement('div');
element.innerHTML = 'Will print AT LEAST once!';
//You need to add it to the body for it to show on the page
document.body.appendChild( element );
}
while(someResult);
JSFiddle showing this: http://jsfiddle.net/azgxh59q/

Jackhammers not changing on mouseover

I'm trying to get the image to change based on one second timer, but the image stays one the first object in the array
the code I have so far is
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Lab 8 - Jackhammer Man</title>
<script type="text/javascript">
var jackhammers = new Array();
jackhammers[0] = "<img src='Images/jackhammer0.gif'>";
jackhammers[1] = "<img src='Images/jackhammer1.gif'>";
jackhammers[2] = "<img src='Images/jackhammer2.gif'>";
jackhammers[3] = "<img src='Images/jackhammer2.gif'>";
jackhammers[4] = "<img src='Images/jackhammer4.gif'>";
jackhammers[5] = "<img src='Images/jackhammer5.gif'>";
jackhammers[6] = "<img src='Images/jackhammer6.gif'>";
jackhammers[7] = "<img src='Images/jackhammer7.gif'>";
jackhammers[8] = "<img src='Images/jackhammer8.gif'>";
jackhammers[9] = "<img src='Images/jackhammer9.gif'>";
jackhammers[10] = "<img src='Images/jackhammer10.gif'>";
var curJackhammer;
function bounce() {
var img = document.getElementsByTagName("img");
var i = 0 ;
for (i = 0; i<10;i++) {
if(jackhammers[i].src == img.src) {
if(i === jackkhammers.length) {
img.src = jackhammers[0].src;
break;
}
img.src = jackhammers[i+1].src;
break;
}
}
}
</script>
</head>
<body>
<img onMouseOver="setInterval(function(){bounce},1000);" onMouseOut="clearInternval(fuction(){bounce};" src="Images/jackhammer0.gif" id="hammer" name="hammerman" alt="Jackhammer Man">
</body>
</html>
The issue I'm coming across is the mouseover event will not activate, I am having trouble finding the error in my code as the debuggers I have aren't finding any. Any help trying to get the mouseover function of the image changing ever so often would be appreciated.
you have a typo if(i === jackkhammers.length)
jackhammers[x] has no src property so to get its value use it without .src
instead of
onMouseOver="setInterval(function(){bounce},1000);"
write:
onMouseOver="setInterval(function(){bounce();},1000);"
var img = document.getElementsByTagName("img");
This returns a NodeList, or an array of elements. You need to access the index of this element with [0]
Or better yet, use querySelector which returns the first element in a NodeList
You keep referring to the src property of items in the jackhammers array:
img.src = jackhammers[0].src;
even though items in that array are strings, not objects.
Also, there's a typo here:
if(i === jackkhammers.length) {
These kinds of errors would be immediately visible the with dev tools of your browser of choise. Put a breakpoint to where you suspect things go wrong and start investigating variables and your assumptions while stepping through the code.
See here: http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820
Updated code changed a few things around based on some advice from my mentor.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Lab 8 - Jackhammer Man</title>
<script type="text/javascript">
var jackhammers = new Array(11);
jackhammers[0] = "Images/jackhammer0.gif";
jackhammers[1] = "Images/jackhammer1.gif";
jackhammers[2] = "Images/jackhammer2.gif";
jackhammers[3] = "Images/jackhammer3.gif";
jackhammers[4] = "Images/jackhammer4.gif";
jackhammers[5] = "Images/jackhammer5.gif";
jackhammers[6] = "Images/jackhammer6.gif";
jackhammers[7] = "Images/jackhammer7.gif";
jackhammers[8] = "Images/jackhammer8.gif";
jackhammers[9] = "Images/jackhammer9.gif";
jackhammers[10] = "Images/jackhammer10.gif";
var curJackhammer = 0;
var direction;
var begin;
function bounce(){
if(curJackhammer == 10)
curJackhammer = 0;
else
++curJackhammer;
document.getElementsByTagName("img")[0].src = jackhammers[curJackhammer].src;
if(curJackhammer == 0)
direction = "up";
else if(curJackhammer == 10)
direction = "down";
document.getElementsByTagName("img")[0].src = jackhammers[curJackhammer];
}
function startBouncing(){
if (begin)
clearInterval (begin);
begin = setInterval("bounce()",90);
}
</script>
</head>
<body>
<h1>Jackhammer Man</h1>
<p><img onMouseOver="startBouncing();" onMouseOut="clearInterval(begin);" src="Images/jackhammer0.gif" height="113" width="100" alt="Image of a man with a jackhammer." /></p>
</body>
</html>
>
Used firebug to step into code, works once I set into it but simply putting a mouse over nothing happens.

document.write alternativ without overwriting the DOM / side

got a problem with the usage of
document.write()
i want to overwrite a div in which a adbanner is loaded and i cant find any solution to this.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
var i = 0;
var newImage;
function refresh() {
i++;
if (i >= 5) {
writeAd();
i = 0;
}
}
function writeAd() {
var arr = box1.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
eval(arr[n].innerHTML)
}
</script>
</head>
<body
<h1>Bilder Random</h1>
<input type="button" onclick="refresh()" value="go!" />
<div id="box1" class="superbanner">
<table cellspacing="0" cellpadding="0" border="0" class="ad1">
<script language="JavaScript">
if (typeof (WLRCMD) == "undefined") {
var WLRCMD = "";
}
if (typeof (adlink_randomnumber) == "undefined") {
var adlink_randomnumber = Math
.floor(Math.random() * 1000000)
}
document
.write('<scr'
+ 'ipt language="JavaScript" src="http://ad.de.doubleclick.net/adj/oms.skol.de/localnews_bilder;oms=localnews_bilder;reg=;nielsen=3b;dcopt=ist'
+ WLRCMD + ';sz=728x90;tile=1;ord='
+ adlink_randomnumber + '?"><\/scr'+'ipt>');
</script>
</table>
</div>
</body>
</html>
My main problem is the document.write() in the adbanner script part.
i can reload the page with 5 clicks on the button but it overwrites the whole DOM
is there any possability to use something else than document.write()
to insert the adbanner at the beginning of the page load and when calling
the function writeAd()?
This is how you should load JS files dynamically:
if (window.isReady) { //after page was loaded, we must manually add new SCRIPT tag into HEAD
var script = document.createElement('script'), head = document.head || document.getElementsByTagName('head')[0];
script.type = 'text/javascript';
script.src = fileName;
head.appendChild(script);
}
else { //otherwise we are still in a progress of creating HEAD or BODY and we can simply write into document
var write = 'write'; //prevents JSlint from saying that document.write is evil ;)
document[write]('<script type="text/javascript" src="' + fileName + '"></script>');
}
To detect if window is loaded:
window.onload = function() { window.isReady = true; }

Modifying street view code, cannot substitute variable as argument

edit1= clearifying sample code
edit2= well this is getting embarassing, now I will post the actual code
I am trying to make a custom interior streetview. I am attempting to convert custom interior shot to be relative to arbitrary starting position by substituting the argument of the function below with variable, but would break the streetview. I am not familiar with javascript.
description:"TEST TEST TEST TSET",latLng:new google.maps.LatLng(54.156654,69.696969)
runs fine.
var demolat = 34.995348; // declared at beginning of function
var demolon = 135.7395;
var wlat = demolat;
var wlon = demolon;
.. lots of code .. // lots of code goes here
description:"TEST TEST TEST TSET",latLng:new google.maps.LatLng(wlat,wlon)
does not work.
full code
the script would not work properly when replaced line described above.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=utf-8"/>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry" type="text/javascript"></script>
<script type="text/javascript" code="maps_code">
var initPosPanoID,initPosPanoData,streetView,map_canvas;
function initialize(){
var neeclat = 35.564157;
var neeclon = 139.714947;
//var demolat = 34.995138;
//var demolon = 135.739689;
var demolat = 34.995348;
var demolon = 135.7395;
var wlat = demolat;
var wlon = demolon;
swbound = new google.maps.LatLng(wlat-0.0003,wlon-0.0003);
nebound = new google.maps.LatLng(wlat+0.0003,wlon+0.0003);
var initPos=new google.maps.LatLng(wlat,wlon);
var mapOptions={zoom:14,center:initPos,mapTypeId:google.maps.MapTypeId.ROADMAP};
var mapDiv=document.getElementById("map_canvas");
map_canvas=new google.maps.Map(mapDiv,mapOptions);
var bounds=new google.maps.LatLngBounds(swbound,nebound);
var overlay=new google.maps.GroundOverlay("./5Bc3IIj.jpg",bounds);
overlay.setMap(map_canvas);
var streetViewOptions={pov:{zoom:1,heading:161,pitch:-2.6}};
var streetViewDiv=document.getElementById('streetview_canvas');
streetViewDiv.style.fontSize="15px";
streetView=new google.maps.StreetViewPanorama(streetViewDiv,streetViewOptions);
streetView.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(mapDiv);
google.maps.event.trigger(map_canvas,"resize");
map_canvas.setStreetView(streetView);
streetView.registerPanoProvider(getCustomPanorama);
var streetViewInitPos=new google.maps.LatLng(wlat,wlon);
// var streetViewInitPos=new google.maps.LatLng(34.995348,135.7395);
var streetviewService=new google.maps.StreetViewService();
var radius=50;
streetviewService.getPanoramaByLocation(streetViewInitPos,radius,function(result,status){
if(status==google.maps.StreetViewStatus.OK){
initPosPanoID=result.location.pano;
initPosPanoData=result;
streetView.setPosition(result.location.latLng);
map_canvas.panTo(result.location.latLng);
}
}
);
google.maps.event.addListener(streetView,"links_changed",createCustomLink);
var map_marker=new google.maps.Marker({map:map_canvas});
google.maps.event.addListener(streetView,"position_changed",function(){
var position=this.getPosition();
var map_bounds=map_canvas.getBounds();
map_canvas.panTo(position);
});
}
function getCustomPanoramaTileUrl(panoID,zoom,tileX,tileY){
return"./"+panoID+'/'+tileX+'-'+tileY+'_s1.jpg';
}
function getCustomPanorama(panoID){
var streetViewPanoramaData={
links:[],copyright:'',tiles:{
tileSize:new google.maps.Size(2048,1024),worldSize:new google.maps.Size(2048,1024),centerHeading:0,getTileUrl:getCustomPanoramaTileUrl
}
};
switch(panoID){
case initPosPanoID:
return initPosPanoData;
case"Position_S":
//var tmp = new google.maps.LatLng(wlat,wlon);
streetViewPanoramaData["location"]={
description:"TEST TEST TEST TSET",latLng:new google.maps.LatLng(3,3)
};
streetViewPanoramaData["copyright"]=""
break;
case"Position_SW":
streetViewPanoramaData["location"]={
description:"TEST TEST TEST TSET",latLng:new google.maps.LatLng(3,3)
};
streetViewPanoramaData["copyright"]=""
break;
}
if("location"in streetViewPanoramaData){
streetViewPanoramaData.location.pano=panoID;
return streetViewPanoramaData;
}
}
function createCustomLink(){
var links=streetView.getLinks();
var panoID=streetView.getPano();
var currentPos=streetView.getPosition();
switch(panoID){
case initPosPanoID:
links.push({description:"テストエリアへ",pano:"Position_S"});
break;
case"Position_S":
links.push({description:"外へ",pano:initPosPanoID});
links.push({description:"SWへ",pano:"Position_SW"});
break;
case"Position_SW":
links.push({description:"Sへ",pano:"Position_S"});
break;
}
if(links.length){ //compute directional pointer label.
var linkPano;
for(var i=0;i<links.length;i++){
linkPano=getCustomPanorama(links[i].pano);
if(linkPano!==undefined){
links[i].heading=google.maps.geometry.spherical.computeHeading(currentPos,linkPano.location.latLng);
}
}
return links;
}
}
google.maps.event.addDomListener(window,'load',initialize);
</script>
<style type="text/css">html,body{width:100%;
height:100%;
margin:0;
position:absolute}#frame,#streetview_canvas{width:100%;
height:100%;
position:relative}#map_canvas{width:250px;
height:250px;
border:2px solid gray;
background-color:#fff}</style>
</head>
<body>
<div id="streetview_canvas"></div>
<div id="map_canvas"></div>
</body>
</html>

How do I refer to the parameter passed to javascript in html?

When I call the script via
<script type="text/javascript"
src="include/javascript/test_something.js?v=1128557"></script>
how do I refer to the variable V passed in the html?
Thanks in Advance!
The most simple way would be to use a server side technology. This is in php.
<?php
$v=1128557;
?>
<script type="text/javascript">
//This will make this value available to javascript too
var val=<?php=$v?>;
</script>
<script type="text/javascript"
src="include/javascript/test_something.js?v=<?php=$v?>"></script>
...
...
...
<div id='baba<?php=$v?>'>
...
...
</div>
This will be translated to the following html
<script type="text/javascript">
//This will make this value available to javascript too
var val=1128557;
</script>
<script type="text/javascript"
src="include/javascript/test_something.js?v=1128557"></script>
...
...
...
<div id='baba1128557'>
...
...
</div>
Get it from the src attribute of the last script element in your page:
var scripts = document.getElementsByTagName("script");
var src = scripts[scripts.length - 1].src;
var v = null;
if (/\?v=(.+)$/.test(src)){
v = RegExp.$1;
}
If it's the first script tag on the page, you can do something like:
var thescripttag = document.getElementsByTagName('script');
var v = thescripttag[0].src.replace(/^[^\?]+\??/,''); //gets everything after the '?'
If it's not the first script tag, you can change [0] to be whichever one it is, or try assigning an id to the script tag (untested).
You can find the appropriate script tag by looking for the desired filename and get the parameters off that .src URL.
function findScriptParams(fname) {
fname = "/" + fname + "?";
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
var pos = scripts[i].src.indexOf(fname);
if (pos != -1) {
return(scripts[i].src.substr(pos + fname.length));
}
}
}
And then you would invoke it like this:
var params = findScriptParams("test_something.js");
if (params) {
// process the params here
}
Change it to
<script type="text/javascript"
src="include/javascript/test_something.php?v=1128557" />
Then create the script test_something.php to be
<?php
echo "var queryString='" . $_SERVER[`QUERY_STRING] . "'\n;";
?>
... rest of javascript here
You can even perform error checking/parsing of the query string using PHP or just get Javascript to do this.
You should do the following:
var scripts = document.getElementsByTagName('script');
var data = {};
for (var i = 0; i < scripts.length; i ++) {
if (!scripts[i].src) {
continue;
}
var value = scripts[i]..substring(scripts[i].indexOf('?') + 1);
var params = value.split('&');
for (var i = 0; i < params.length; i ++) {
params[i] = params[i].split('=');
data[params[i][0]] = params[i][1];
}
}
EDIT: Just incorporated some of the tips from others, and added them to my own answer.
JavaScript only has access to URL data for the page it's being executed on via window.location. It does not have access to any HTTP request variables passed to the javascript file itself unless the web server explicitly serializes it to JavaScript in the output.
One hack/workaround would be to find the script tag, get the src attribute, parse the URL and extract the GET parameters you need.
function getParamsFor(script) {
var params, anchor, paramArray, keyVal, tag, scripts;
scripts = document.getElementsByTagName("script");
// Make sure [].filter exists beforehand
tag = Array.prototype.filter.call(scripts, function (e) {
return e.src.indexOf(script) > -1;
})[0];
if (tag) {
anchor = document.createElement("a");
anchor.href = tag.src;
paramArray = anchor.search.substring(1).split('&');
params = {};
for(var i = 0; i < paramArray.length; i++) {
keyVal = paramArray[i].split('=');
params[unescape(keyVal[0])] = (typeof keyVal[1] != "undefined") ? unescape(keyVal[1]) : keyVal[1];
}
return params;
}
}
var o = getParamsFor("test_something.js");
o.v; // 112..

Categories

Resources