Image alternating function alternates wrong image - javascript

I'm new to HTML, JavaScript, CSS, and am taking a Web Design class. I'm required to make a banner ad that alternates between two different images (banner1.jpg & banner2.jpg). The problem I'm having is when my site loads it displays banner1.jpg above the <h2>, and court.jpg below. Then it changes court.jpg to banner2.jpg then to banner1.jpg, alternating back & forth between the two banners. The banner1.jpg above the <h2> stays static. Here's the relevant code:
<script type="text/javascript">
/* <![CDATA[ */
var curImage="banner1";
function bannerAd() {
if (curImage == "banner2") {
document.images[1].src = "images/banner1.jpg";
curImage = "banner1";
}
else {
document.images[1].src = "images/banner2.jpg";
curImage = "banner2";
}
}
/* ]]> */
</script>
</head>
<body onload="var changeImages=setInterval('bannerAd()', 2000);">
<header>
<h1>Basketball Almanac</h1>
</header>
<section class="main">
<img src="images/banner1.jpg" alt="Banner image" />
<h2>Basketball Analysis</h2>
<p><span class="companyname">Basketball Almanac</span> is your one-stop site for in-depth basketball analysis and statistics.</p>
<img class="main" src="images/court.jpg" alt="NBA Court" />
How do I make it so only banner1.jpg changes? Thanks in advance for any help, and let me know if it would help to include more of the code here.

Simple, in javascript, arrays are 0 based, so the frist object is [0]
So you want
var curImage="banner1";
function bannerAd() {
if (curImage == "banner2") {
document.images[0].src = "images/banner1.jpg";
curImage = "banner1";
}
else {
document.images[0].src = "images/banner2.jpg";
curImage = "banner2";
}
}
or to simplify it a little
var curImage="images/banner2.jpg";
function bannerAd() {
if (curImage == "images/banner1.jpg") {
curImage= "images/banner2.jpg";
}
else {
curImage = "images/banner1.jpg";
}
document.images[0].src = curImage;
}

var curImage="images/banner2.jpg";
function bannerAd() {
if (curImage == "images/banner1.jpg") {
curImage= "images/banner2.jpg";
}
else {
curImage = "images/banner1.jpg";
}
document.images[0].src = curImage;
}

var curImage="banner1";
function bannerAd(n) {
if (curImage == "banner2") {
document.images[n].src = "images/banner1.jpg";
curImage = "banner1";
}
else {
document.images[n].src = "images/banner2.jpg";
curImage = "banner2";
}
}
//bannerAd(1)
<body onload="var changeImages=setInterval('bannerAd(0)', 2000);">
<header>
<h1>Basketball Almanac</h1>
</header>
<section class="main">
<img src="images/banner1.jpg" alt="Banner image" />
<h2>Basketball Analysis</h2>
<p><span class="companyname">Basketball Almanac</span> is your one-stop site for in-depth basketball analysis and statistics.</p>
<img class="main" src="images/court.jpg" alt="NBA Court" />

Related

JavaScript not working for all HTML pages

I am working on the tablet's display of a Pepper robot; I have a functional HTML index page comprising a list of questions—each question redirects to its respective HTML when clicked on—, 2 volume buttons and 2 other buttons—one that pops up an instruction image and the other one that closes the index page and gets back to the splash screen, which when clicked upon, reveals the index page. So far everything is working. The issue is that when I click a question—I get redirected to its HTML page, but then I get stuck there, as neither the 2 volume buttons nor the 2 other buttons work;
I made sure to include the following in each HTML page:
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
I also reused the same JavaScript functions that worked for the index page.
I commented out some line:
btnPrevious.addEventListener('click', goToPreviousPage);
because I noticed it prevented the splash screen from disappearing when clicked on—i.e., the visibility attribute stays on visible instead of switching to hidden thus revealing the index page, but still, the 3 remaining buttons don't work anyway.
Here is my faq.js code:
/* global QiSession */
var serviceName = 'ADFAQ';
var volumeUpEvent = serviceName + '/VolumeUp';
var volumeDownEvent = serviceName + '/VolumeDown';
var volumeData = serviceName + '/Volume';
/* Clickable buttons */
var btnReturn = document.getElementById('return');
var btnHelp = document.getElementById('call_help');
var btnPrevious = document.getElementById('previous_page');
var btnVolUp = document.getElementById('volume-up');
var btnVolDown = document.getElementById('volume-down');
/* Help image and splash screen */
var helper = document.getElementById('helper');
var img = document.getElementById('click_on_me');
var memory;
var volume;
var audioDevice;
QiSession(connected, disconnected);
function connected (s) {
console.log('QiSession connected');
var questions = document.getElementById('questions');
/* Associating buttons to their respective functions */
btnHelp.addEventListener('click', showHelper);
btnReturn.addEventListener('click', closeQuestions);
//btnPrevious.addEventListener('click', goToPreviousPage);
btnVolUp.addEventListener('click', raiseVolume);
btnVolDown.addEventListener('click', lowerVolume);
img.addEventListener('click', loadQuestions);
questions.addEventListener('click', clickOnQuestion);
s.service('ALMemory').then(function (m) {
m.subscriber(serviceName + '/DialogEnded').then(function (subscriber) {
subscriber.signal.connect(hideQuestions);
});
m.subscriber(serviceName + '/Pepper').then(function (subscriber) {
subscriber.signal.connect(displayPepperHTML)
});
m.subscriber(serviceName + '/RaiseVolume').then(function (subscriber) {
subscriber.signal.connect(raiseVolume);
});
m.subscriber(serviceName + '/LowerVolume').then(function (subscriber) {
subscriber.signal.connect(lowerVolume);
});
memory = m;
});
s.service('ALAudioDevice').then(function (a) {
a.getOutputVolume().then(assignVolume);
audioDevice = a
});
}
function disconnected () {
console.log('QiSession disconnected');
}
function assignVolume(value){
volume = value;
}
function raiseVolume (event) {
var changed = 0;
if(volume < 100) {
volume = Math.min(volume + 5, 100);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeUpEvent, changed);
}
function lowerVolume (event) {
var changed = 0;
if(volume > 30) {
volume = Math.max(volume - 5, 0);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeDownEvent, changed);
}
function showHelper (event) {
if (btnHelp.innerHTML === '?') {
helper.style.opacity = '1';
helper.style.zIndex = '1';
btnHelp.innerHTML = '←';
} else {
helper.style.opacity = '0';
helper.style.zIndex = '-1';
btnHelp.innerHTML = '?';
}
btnHelp.blur();
}
function loadQuestions (event) {
memory.raiseEvent(serviceName + '/LoadQuestions', 1);
img.style.visibility = 'hidden';
}
function goToPreviousPage () {
window.location.href = "index.html";
}
function displayPepperHTML() {
window.location.href = "pepper.html";
}
function closeQuestions (event) {
if(location.href != "index.html")
{window.location.href = "index.html";}
memory.raiseEvent(serviceName + '/CloseQuestions', 1);
btnReturn.blur();
}
function hideQuestions (data) {
if (data !== 0) {
img.style.visibility = 'visible';
helper.style.opacity = '0';
btnHelp.innerHTML = '?';
}
}
function clickOnQuestion (event) {
memory.raiseEvent(serviceName + '/' + event.target.id, 1);
}
Here is my non-functioning pepper.html code:
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Pepper</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=1280, user-scalable=no" />
<link type="text/css" rel="stylesheet" href="css/style.css" />
<link type="text/css" rel="stylesheet" href="css/faq.css" />
</head>
<body>
<header>
<h1>Bla bla bla</h1>
<span class="buttons">
<button id="previous_page" class="button-help"> ← </button>
<button id="return" class="button-return">X</button>
</span>
<div id="helper" class="pop-up">
<img src="img/interactionscreen_frf.png" alt="Bla bla bla">
</div>
</header>
<ul id="questions">
<p>
Bla bla bla
</p>
<div class="volume-part">
<div id="volume-up" class="Click-me">+</div>
<img src="img/speaker.png" alt="Bla bla bla" style="vertical-align: middle;">
<div id="volume-down" class="Click-me">-</div>
</div>
</ul>
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
</body>
</html>
Thank you for your help.
I am expecting the pepper.html page to respond to both the volume and ← and X buttons, as the index.html should, since they use the exact same Javascript.
I was able to find some workaround: creating one JavaScript file for each HTML page, this is redundant and non-optimal I know, but at least it works.
This also made me realize that the commented-out line was blocking the program because the index.html page doesn't use the previous_page button, that's what led me to make a JS file for each HTML page.
If anybody has any other suggestions I am all ears.
Edit: I reduced the number of JS scripts to only 2. One for the index.html and the other for the identically-structured html pages of the other questions.

Audio not loading on mobile browser (Plyr player)

I have found a nice HTML 5 audio player with playlist and artwork based on plyr. It works nicely on my desktop browser, but on my mobile device (iOS), it's not playing after pressing play. There's a codepen to demonstrate:
https://codepen.io/gifteconomist/pen/LREwXv
I've tried debugging via mobile browser, but no errors are shown.
Any ideas what could be going wrong here? Thanks a lot!
html
<head>
<meta charset="UTF-8">
<title>Responsive Audio Playlist with Cover Art Player</title>
<link rel='stylesheet' href='http://cdn.plyr.io/1.6.13/plyr.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<main>
<section>
<div class="playlist">
<div class="plyr">
<audio controls></audio>
</div>
<ul class='playlist--list'>
<li data-id="0" data-image="https://www.callofduty.com/content/dam/atvi/callofduty/hub/main-hub/iw-hub/games/key-art/aw-key-art.jpg" data-audio="http://cdn.ascap.com/Member/Jach_Wall/BlackOps3.mp3">Call of Duty: Black Ops 3
<span class="artist">Jack Wall</span>
</li>
<li data-id="1" data-image="https://seussblog.files.wordpress.com/2013/03/143056e8473127ab6a665773884132bc.jpg" data-artist="StarBelly" data-title="Broken Hearts in Stereo" data-audio="http://cdn.ascap.com/network/audioportraits/Starbelly/03.mp3">Broken Hearts in Stereo
<span class="artist">Starbelly</span>
</li>
<li data-id="2" data-image="http://east.myna1.net/wp-content/uploads/sites/24/2016/03/nathan-east-pic.jpg" data-audio="http://cdn.ascap.com/Member/Nathan_East/Approach.mp3">Approach
<span class="artist">Nathan East</span>
</li>
</ul>
</div>
</section>
</main>
<script src='http://cdn.plyr.io/1.6.13/plyr.js'></script>
<script src="js/index.js"></script>
</body>
js
//Using JS Audio Player Plyr
plyr.setup(document.querySelector('.plyr'));
var radio = document.querySelector('.plyr').plyr;
var player = document.querySelector('.playlist');
var playerControls = document.querySelector('.plyr__controls');
var songs = player.querySelectorAll('.playlist--list li');
var i;
var active = null;
for(i = 0; i < songs.length; i++) {
songs[i].onclick = changeChannel;
}
setSource( getId(songs[0]), buildSource(songs[0]) );
document.querySelector('.plyr').addEventListener('ended', nextSong);
function changeChannel(e) {
setSource( getId(e.target), buildSource(e.target), true );
setArt(e.target);
}
function getId(el) {
return Number(el.getAttribute('data-id'));
}
function buildSource(el) {
var obj = [{
src: el.getAttribute('data-audio'),
image: el.getAttribute('data-image'),
artist: el.getAttribute('data-artist'),
type: 'audio/ogg'
}];
console.log(obj[0].image);
return obj;
}
function setSource(selected, sourceAudio, play) {
if(active !== selected) {
active = selected;
playerControls.style.background = "linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,0.99) 100%), url("+sourceAudio[0].image+")";
radio.source({
type: 'audio',
title: 'test',
poster: sourceAudio[0].image,
sources: sourceAudio
});
for(var i = 0; i < songs.length; i++) {
if(Number(songs[i].getAttribute('data-id')) === selected) {
songs[i].className = 'active';
} else {
songs[i].className = '';
}
}
if(play) {
radio.play();
}
} else {
radio.togglePlay();
}
}
function setArt(e) {
console.log(e);
}
function nextSong(e) {
var next = active + 1;
if(next < songs.length) {
setSource( getId(songs[next]), buildSource(songs[next]), true );
}
}
Safari browser doesn't support ogg audio file type make sure you are not using this file type in your browser and also make sure the extension of audio file is correct.

Using Timber Framework counter with a URL API that continuously counts up

My skills with jquery and such are limited when it comes to this. For our website we are using timber framework with some of the plugins. I would like to use their counter but have the counter go up in real time. Please help if you can. Thank you in advance. in the HTML i have wrote realtime where i would like the counter to be realtime. I hope i have provided enough information. So in summary what i need help with is i would like to use the timber framework style and look but have the counter be realtime instead of stopping at a number and being a very basic counter.
HTML
`
<div class="column width-4 offset-4 center">
<div class="counter-wrapper">
<p style="font-size:60px;" class="counter lead"><span class="stats-1" data-count-from="1300000" data-count-to="realtime" >1000000</span></p>
<p style="font-size:36px;" class="lead">Hotspots</p>
</div>
</div>
`
Javascript
<script>
$( document ).ready( function(){
$( '.stats-1' ).counter();
$( '.stats-2' ).counter({
autoStart: true
});
});
</script>
Realtime counter URL
https://reelsonar-services.com/api/v1/hotspot_count
OUR COUNTER from a sample site
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.flipcountdown.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.flipcountdown.css" />
<script>
var hotspot_count = 1000000;
function fetch_waterbody_count() {
var url="https://reelsonar-services.com/api/v1/hotspot_count";
//var url="http://reelsonar-services.com:8085/hotspot_count";
var html = [];
$.getJSON( url, function( data ) {
console.log( data );
$.each(data, function(index, d){
html.push("Hotspots: ", d.hotspot_count, "<br>");
var count = parseInt( d.hotspot_count );
if( count != hotspot_count) {
hotspot_count = count;
update_counter( hotspot_count )
}
});
});
}
function update_counter( count ) {
jQuery('#flipcountdown').flipcountdown({size:'md',tick:count});
}
function reset_counter( count ) {
jQuery('#flipcountdown').flipcountdown({size:'md',tick:count});
}
function pulse_hotspot() {
(function pulse(back) {
$('#hotspot_img').animate(
{
'font-size': (back) ? '25px' : '35px',
opacity: (back) ? 1 : 0.5
}, 1200, function(){pulse(!back)});
$('#hotspot_img img').animate(
{
'width': (back) ? '125px' : '112px'
}, 1200);
})(false);
}
</script>
<body style="background: lightblue;text-align: center">
<script>
$(document).ready(function(){
$("#fetchButton").click(function(event){
fetch_waterbody_count();
});
$("#addOneButton").click(function(event){
hotspot_count += 1;
update_counter( hotspot_count );
});
$("#addTenButton").click(function(event){
hotspot_count += 10;
update_counter( hotspot_count );
});
$("#resetButton").click(function(event){
reset_counter(1000000);
});
setInterval(fetch_waterbody_count, 2000);
pulse_hotspot();
});
</script>
<script>
jQuery(function(){
jQuery('#flipcountdown').flipcountdown({size:'md',tick:hotspot_count}); <!-- Medium sized -->
})
</script>
<div style="font-size: x-large; padding-bottom: 1em">ReelSonar Global Hotspot Counter</div>
<div style="font-size: large; padding-bottom: 1em">Displays Hotspots as they are created by our users in real time.</div>
<pre>(Retrieves Hotspot count every two seconds)</pre>
<div id="hotspot_img"><img src="hotspot.png" /></div>
</body>
</html>
This is a polling issue: send Ajax request periodically, get the latest number and display it on screen (using Timber's counter to add animation effect).
Here is a working example. Please note it is a bit complex because the returned data is an array, not a single object (need to handle the situation when multiple numbers are returned in one array):
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="lib/css/components/timber.css" />
</head>
<body>
<span data-count-from="1" data-count-to="1" id="counter"></span>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="lib/js/plugins/jquery.tm.counter.js"></script>
<script type="text/javascript">
$(function() {
var queue = [];
var url="https://reelsonar-services.com/api/v1/hotspot_count";
var counter = document.getElementById('counter');
var $counter = $(counter);
var latestNum = null;
getData(true);
setInterval(function() {
getData();
}, 30000);
function getData(init) {
$.getJSON(url, function(data) {
if (init) {
var num = data.shift().hotspot_count;
counter.dataset.countFrom = num;
$counter.text(formatNumber(num));
}
queue = queue.concat(data);
playCount();
});
}
function playCount() {
if (queue.length === 0) {
return;
}
var countTo = queue.shift().hotspot_count;
if (countTo && countTo === latestNum) {
playCount();
}
latestNum = countTo;
counter.dataset.countTo = countTo;
$counter.counter();
setTimeout(function() {
counter.dataset.countFrom = countTo;
if (queue.length > 0) {
playCount();
}
}, 1000);
}
function formatNumber( number ) {
return number.toString().replace( /(\d)(?=(\d{3})+$)/g, '$1,' );
}
});
</script>
</body>
</html>

switch from image to random image onclick with JavaScript

I'm trying to build something that would resemble a slide show, where you have an image and when you click on it, it is replaced by another randomly in my series of images. I first tried with simple html, but of course the images don't switch randomly. So I did my research and found that it could be done with an array in Javascript. I just don't really know a lot about javascript…
This is what I could find but it doesn't work, I'm sure there is a stupid mistake in there that I can't see:
this is my javascript
function pickimg2() {
var imagenumber = 2 ;
var randomnumber = Math.random();
var rand1 = Math.round((imagenumber-1) * randomnumber) + 1;
myImages1 = new Array();
myImages1[1] = "img_01.gif";
myImages1[2] = "img_02.gif";
myImages1[3] = "img_03.gif";
myImages1[4] = "img_04.gif";
myImages1[5] = "img_05.gif";
myImages1[6] = "img_06.gif";
myImages1[7] = "img_07.gif";
myImages1[8] = "img_08.gif";
myImages1[9] = "img_09.gif";
var image = images[rand1];
document.randimg.src = "myImages1";
}
there is my html
<!DOCTYPE html>
<html>
<head>
<title>mur</title>
<link rel="stylesheet" href="style.css">
<link rel="JavaScript" href="script.js">
</head>
<body onLoad="pickimg2">
<div class="fenetre">
<img src="img_01.gif" name="randimg" border=0>
</div>
</body>
</html>
If someone has another solution I'm open to it!
Fix your script link like RamenChef mentioned:
<script type="text/javascript" src="script.js"></script>
Here's the updated code, check console.log to see the different image urls getting requested.
var myImages1 = new Array();
myImages1.push("img_01.gif");
myImages1.push("img_02.gif");
myImages1.push("img_03.gif");
myImages1.push("img_04.gif");
myImages1.push("img_05.gif");
myImages1.push("img_06.gif");
myImages1.push("img_07.gif");
myImages1.push("img_08.gif");
myImages1.push("img_09.gif");
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function pickimg2() {
document.randimg.src = myImages1[getRandomInt(0, myImages1.length - 1)];
}
<div class="fenetre">
<a href="#" onClick="pickimg2();return false;">
<img src="img_01.gif" name="randimg" border=0>
</a>
</div>
this code bellow is working. I hope it's what you were asking for
var images = [
"http://img1.science-et-vie.com/var/scienceetvie/storage/images/galerie/deepsea-challenge-le-film-de-james-cameron-livre-des-images-inedites-des-grands-fonds-marins-5165/19818-1-fre-FR/Deepsea-challenge-le-film-de-James-Cameron-livre-des-images-inedites-des-grands-fonds-marins_square500x500.jpg",
"http://static.mensup.fr/photos/145240/carre-premieres-images-officielles-pour-assassin-s-creed-rogue.jpg",
"http://www.pnas.org/site/misc/images/16-01910.500.jpg" ];
init();
function random_image(images) {
var random = randomize(images);
while(images[random] === document.getElementById("image").src){
random = randomize(images)
}
document.getElementById("image").src = images[random].toString();
}
function randomize(array){
return Math.floor((Math.random() * (array.length)));
}
function init() {
document.getElementById("image").addEventListener("click", function(){
random_image(images);
});
random_image(images);
}
<!DOCTYPE html>
<html>
<head>
<title>Bonjour</title>
</head>
<body >
<div class="fenetre">
<img id="image" src="" name="randimg" >
</div>
</body>
</html>

Cycle pictures using an array in JS and HTML

this works on a button click and that is how it is meant to be. The problem lies in the fact that it uses hidden images, instead of images stored in an array. Could you please show me how to do it so that it is images stored in an array.
<!doctype html>
<html>
<body>
<div id="splash">
<img src="TrafficLightRed.gif" alt="" id="mainImg">
</div>
<div id="wrapper">
<div>
<button id="clickme" onclick="changeLight();">Click to change</button>
<img src="TrafficLightRed.gif" hidden>
<img src="TrafficLightYellow.gif" hidden>
<img src="TrafficLightGreen.gif" hidden>
</div>
</div>
<script>
function changeLight() {
var currentImg = document.getElementById("mainImg");
for(var i=1;i<3;i++) {
if(document.images[i].src == currentImg.src) {
currentImg.src = document.images[i + 1].src;
return;
}
}
currentImg.src = document.images[1].src;
}
</script>
</body>
</html>
You would store the image's src in an array:
imagesArray = ["TrafficLightRed.gif","TrafficLightYellow.gif","TrafficLightGreen.gif" ];
And use the array in place of document.images[i + 1].src:
...
for(var i=0;i<imagesArray.length;i++) {
if(imagesArray[i] == currentImg.src) {
currentImg.src = imagesArray[i];
return;
}
}
...
This should do the work:
...
<script>
var images = ["TrafficLightRed.gif", "TrafficLightYellow.gif", "TrafficLightGreen.gif"];
var currentIndex = 0;
function changeLight() {
var currentImg = document.getElementById("mainImg");
currentImg.src = images[(currentIndex++) % images.length];
}
</script>
...
Now you can add more images to array images and it will automatically loop through this array.

Categories

Resources