Javascript Dynamic pointer allocation - javascript

I'm wondering whether I can assign the pointer of a variable as something along the lines of
"image"+i+".src"
I've tried using eval, because that's the only suggestion I've found, but I'm being thrown a undefined variable error. Here's my code, if someone wouldn't mind taking a look:
<html>
<head>
<script type="text/javascript">
<!--
m = 0
x = 0
image=[ //Initializes the Array for Image URLs, Add object by adding the full URL in "" with , in between each entry
"http://i.imgur.com/OaElB10.jpg",
"http://i.imgur.com/NTYiEB9.jpg",
"http://i.imgur.com/X1jreGc.jpg"]
function ImgPreloadHandler()
{
l = image.length
for(t=0; t<l; t++)
{
var image+t = new image()
image+t = image[t]
}
}
ImgPreloadHandler()
//-->
</script>
</head>
<body>
<img src="http://i.imgur.com/mv3sV8m.png" name="slide" width="796" height="600" />
<script>
function slideit()
{
var step = 0
var z = step
if (!document.images)//if browser does not support the image object, exit.
return
document.images.slide.src=
if (step<x)
step++
else
step=1
setTimeout("slideit()",2500)//call function "slideit()" every 2.5 seconds
}
slideit()
</script>
</body>
</html>

You can't create a dynamic variable name. But there's plenty of other solutions.
Why not create an Object that contains your image values?
var images = {};
for(t=0; t<l; t++) {
images[image + t] = image[t];
}
console.log(images);
> {
image0: "http://i.imgur.com/OaElB10.jpg",
image1: "http://i.imgur.com/NTYiEB9.jpg",
image2: "http://i.imgur.com/X1jreGc.jpg"
}
By the way, don't use eval :)

Related

Automatically load next image from array everytime user enters website

So this code selects random image whenever a person loads my website, how can I change the code so that images are selected sequentially from first to last everytime a person loads the website and then again resets to first image when the counter reaches the end?
P.s- The code works fine on hosting server, here it gives an error i don't know why.
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
var randomNum = Math.floor(Math.random() * myPix.length);
document.getElementById("myPicture").src = myPix[randomNum];
}
<!DOCTYPE html>
<html>
<head>
<title>Random Image</title>
<script src="thumb.js"></script>
</head>
<body>
<img src="images/spacer.gif" id="myPicture" alt="some image">
</body>
</html>
You can use localstorage to achieve this. When the user enters the website, you can do something like:
var pictureIndex = localstorage.getItem("pictureIndex");
But since it may be the user's first visit, it would be better to have:
var pictureIndex = localstorage.getItem("pictureIndex") || 0;
Then, you just increment the pictureIndex and perform a modulo operation (for the case when this is the last image)
pictureIndex = (pictureIndex + 1) % myPix.length;
To save this index, you can use
localStorage.setItem('pictureIndex', pictureIndex);
Next time when the user refreshes the page (or comes back), he will get the next picture in your array.
The final code should look like this:
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
var pictureIndex = window.localStorage.getItem("pictureIndex") || 0;
pictureIndex = (pictureIndex + 1) % myPix.length;
window.localStorage.setItem("pictureIndex", pictureIndex);
document.getElementById("imgid").innerHTML = pictureIndex;
document.getElementById("myPicture").src = myPix[pictureIndex];
}
<!DOCTYPE html>
<html>
<head>
<title>Random Image</title>
<script src="thumb.js"></script>
</head>
<body>
Press "Run" multiple times to cycle through the images.
Currently showing: <span id="imgid"></span>
<img src="images/spacer.gif" id="myPicture" alt="some image">
</body>
</html>
Note that the above code might not work here (but you can test it locally) due to some security restrictions from jsfiddle. A working version can be accessed >here<
function choosePic() {
var local_item = 0;
if(localStorage.getItem('pic_key')){
local_item = parseInt(intvlocalStorage.getItem('pic_key'));
}
if(local_item >= myPix.length){
local_item = 0;
}
localStorage.setItem('pic_key', local_item + 1);
document.getElementById("myPicture").src = myPix[local_item];
}
You can use LocalStorage to achieve this. When the user enters the website, you can store the key and increment it.
Use local storage to save the data you need [e.g. visited = 3(3rd time the same person visited your website)]
Your js code can be implemented like this:
window.onload = choosePic;
var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");
function choosePic() {
if (localStorage.getItem('visited') == null)
{
document.getElementById("myPicture").src = myPix[0];
localStorage.setItem('visited', 1);
}
else if (localStorage.getItem('visited') >= myPix.length)
{
localStorage.setItem('visited', 0);
document.getElementById("myPicture").src = myPix[localStorage.getItem('visited')];
}
else
{
document.getElementById("myPicture").src = myPix[localStorage.getItem('visited')];
localStorage.setItem('visited', localStorage.getItem('visited') + 1);
}
}

parseInt() returns NaN instead of integer

I'm trying to implement a route-finder using javascript. To do so, I create a grid from a 2d array, and insert 'x' (walls), 'o' (open space), '0' (start), and 'g' (goal). I would like to increment the open squares from the start to the goal, so I end up with something that looks like this: '0',1,2,3,4,5 ... g
However, my grid never goes past 0 and 1. My console keeps returning NaN for the remaining open spaces and I suspect it's a typeError from using parseInt(). Please see my code below - I really appreciate your help.
<!DOCTYPE html>
<head>
<link rel='stylesheet' type='text/css' href = 'routes.css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body></body>
<script>
//o is an open space x is a wall
var a = [['0','o','x','x'],
['x','o','o','o'],
['x','o','x','o'],
['x','o','o','g']];
/*printed grid looks like this
var a = [[0,1,'x','x'],
['x',NaN,NaN,NaN],
['x',NaN,'x',NaN],
['x',NaN,NaN,'g']];*/
function move(startR,startC){ //(0,0) startR,startC
var north = startR-1;
var south = startR+1;
var east = startC+1;
var west = startC-1;
//discard all the out of bounds locations
if (north<0){north=startR;}
if (south>3){south=startR;}
if (east>3){east=startC;}
if (west<0){west=startC;}
if (a[north][startC]=='o'){newLocation(north,startC,startR,startC);}
if (a[south][startC]=='o'){newLocation(south,startC,startR,startC);}
if (a[startR][west]=='o'){newLocation(startR,west,startR,startC);}
if (a[startR][east]=='o'){newLocation(startR,east,startR,startC);}
}
//newLocation() increments square I just moved to and pass the new location to the function 'move '
function newLocation(northSouth,eastWest,origR,origC){
var origValue = parseInt(a[origR,origC]);
console.log(origValue); //prints NaN to console
var newValue = ++origValue;
a[northSouth][eastWest]=newValue;
console.log(a[origR,origC]);
return move(northSouth,eastWest);
}
move(0,0);
//print board to screen
for (r=0;r<4;r++){
document.write('<br>');
for (c=0;c<4;c++){
var l = document.createElement('div');
var t = document.createTextNode(a[r][c]);
$(l).addClass('letterboxes');
l.appendChild(t);
document.body.appendChild(l);
// document.body.appendChild(letter);
}
}
</script>
</html>

doesnt get in the if statement javascript DOM

so I have to get the bigger salary of the average salary and to print the name of the person, but I don't get in the if at least the alert says so. Here is my code:
<html>
<body>
<script type="text/javascript">
xDOC = new ActiveXObject("Microsoft.XMLDOM");
xDOC.async = "false";
xDOC.load("pti_project.xml");
x = xDOC.getElementsByTagName("person");
alert(x.length);
var avgsal = 11450 / x.length;
for (var i = 0; i < x.length; i++) {
var salary = x[i].getElementsByTagName("salary");
if (salary * 1 > avgsal * 1) {
alert("1");
var person = x[i].getElementsByTagName("name");
document.write(person[0].childNodes[0].nodeValue);
}
}
document.write(avgsal);
</script>
</body>
</html>
No clue why is this happens, it should work.
How its name says, the method getElementsByTagName() returns a collection of objects, not their values.
Look at the example in this page: https://msdn.microsoft.com/en-us/library/ms765549(v=vs.85).aspx
The result of the function is iterated with a for loop to get each matched element and then its xml property is printed.
Something like:
(salary.length > 0 ? parseFloat(salary.item(0).xml) : 0)
would work for you instead of only salary.
This expression will check if the collection is not empty and if so will get the content of first element. Otherwise will return zero.
Here is my answer to my question I needed little time , but I made it . So here is the code if somebody needs help with such type of situation :
<html>
<body>
<script type="text/javascript">
xDOC=new ActiveXObject("Microsoft.XMLDOM");
xDOC.async="false";
xDOC.load("pti_project.xml");
x=xDOC.getElementsByTagName("person");
var avgsal = 11450/x.length;
for(var i=0; i<x.length; i++)
{
var salary=x[i].getElementsByTagName("salary");
if(salary[0].childNodes[0].nodeValue>avgsal*1)
{
var person=x[i].getElementsByTagName("name");
document.write(person[0].childNodes[0].nodeValue);
document.write("<br>");
}
}
</script>
</body>
</html>

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.

Simple Javascript not working in IE, works in Firefox

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>

Categories

Resources