Jackhammers not changing on mouseover - javascript

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.

Related

Some issues with an image carousel (JavaScript)

I'm making a image carousel to get some more experience.
I have an acf gallery in the back-end where i add my images.
This is the code that i use here:
<div class="images">
<img id="carousel_images_top" src="" alt="">
<div class="top_button next">Next</div>
<div class="top_button prev">Prev</div>
</div>
<script>
var imageList = [];
<?php
$images = get_field('image_carousel');
foreach($images as $img) {
echo "imageList.push('" . $img['url'] . "');";
}
?>
var imageTag = document.querySelector('#carousel_images_top');
imageTag.src = imageList[0];
function next() {
console.log(imageTag.src)
var curIndex = imageList.indexOf(imageTag.src);
imageTag.src = imageList[(curIndex+1) % imageList.length];
};
function prev() {
console.log(imageTag.src)
var curIndex = imageList.indexOf(imageTag.src);
imageTag.src = imageList[(curIndex-1 + imageList.length) % imageList.length];
};
document.querySelector('.next').addEventListener('click', next);
document.querySelector('.prev').addEventListener('click', prev);
</script>
I can see the first image in the array, and i can go back one to see the last one, but I can't go more than one back, and then forward to the first one again.
I do not get any errors at all, and I have tried to find out where the error is, but in the array, all of my 6 images is listed and the buttons are working.
I'm guessing there is an error in the curIndex variable, but I can't realy see what.
Anyone that can have a quick look and point me in the right direction?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Static Template</title>
</head>
<body>
<div class="images">
<img id="carousel_images_top" src="" alt="">
<p>Current Index: <span id="currentindex"></span></p>
<div class="top_button next">Next</div>
<div class="top_button prev">Prev</div>
</div>
<script>
var imageList = [
'https://tse1-mm.cn.bing.net/th?id=OIP.2bdrFgmVuK6LO0ggJdNPZAHaFP&w=152&h=105&c=8&rs=1&qlt=90&dpr=1.5&pid=3.1&rm=2',
'https://tse1-mm.cn.bing.net/th?id=OIP.yP3sLQkAOswh1wDZq21NtwHaFj&w=144&h=105&c=8&rs=1&qlt=90&dpr=1.5&pid=3.1&rm=2',
'https://tse1-mm.cn.bing.net/th?id=OIP.FEUTSwbKW9ndBYzd-oI8OQHaIN&w=99&h=105&c=8&rs=1&qlt=90&dpr=1.5&pid=3.1&rm=2',
];
var imageTag = document.querySelector('#carousel_images_top');
var currentindexTag = document.getElementById('currentindex');
imageTag.src = imageList[0];
function next() {
//console.log(imageTag.src)
var curIndex = imageList.indexOf(imageTag.src);
imageTag.src = imageList[(curIndex+1) % imageList.length];
currentindexTag.innerHTML = curIndex;
};
function prev() {
//console.log(imageTag.src)
var curIndex = imageList.indexOf(imageTag.src);
imageTag.src = imageList[(curIndex-1 + imageList.length) % imageList.length];
currentindexTag.innerHTML = curIndex;
};
document.querySelector('.next').addEventListener('click', next);
document.querySelector('.prev').addEventListener('click', prev);
</script>
</body>
</html>
Follow the code you write, the images replacement does work correctly except the input of images array has same url.
Because the indexOf method returns the first index at which a given element can be found in the array, or -1 if it is not present.
var images = ['1.png', '1.png', '1.png'];
//no matter how many times to execute images.indexOf('1.png'), it's always return 0.
So, the better solution is that replacing of the curIndex with a global number, like below:
var curIndex = 0;
function prev() {
...
curIndex -= 1
}
function next() {
...
curIndex += 1;
}
This solution should be avoiding the problem you meet.
That's an example and it makes some evidences for the correct of your script.
There are two directions to find the problem is. One, to check the images input, and another, try to debug the code in reality environment.

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);
}
}

Check if shown (randomised) image is the same as last (randomised) image (jQuery & JavaScript )

(Before anything, you should know that my JS skills are very basic)
I'm trying to make my own "rapid sorting" from the game "BrainWars" on smartphones.
Basically what it should do is:
Step 1: randomise one of the 3 pictures available and show the image.
Step 2: if this image is the same as the last one ( do something )
Step 3: If this image is NOT the same as the last one ( do something else )
For now , I have a folder named "images" with 3 png's inside it.
So far I have this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
var random_images_array = ['1.png', '2.png', '3.png'];
var lastImage = "";
function getRandomImage(imgAr, path) {
path = path || 'images/'; // Default path hier opgeven
var num = Math.floor(Math.random() * imgAr.length);
var img = imgAr[num];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr);
document.close();
}
$(function() {
$('#btn').click(function() {
getRandomImage(random_images_array, 'images/');
setTimeout(function() {
getRandomImage(random_images_array, 'images/');
}, 2000);
});
});
</script>
</head>
<body>
<button id="btn">GO</button>
</body>
</html>
How can one achieve this ?
What about creating a lastImage variable...
var random_images_array = ['1.png', '2.png', '3.png'];
var lastImage="";
Then:
var img = imgAr[num];
if (img==lastImage) {do something}
else {lastImage=img; ... document.write(imgStr);}

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/

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