I am working with a script to change images in an HTML site when the user clicks on it. the script works a treat to have this kind of slideshow without the menu.
but now I want (from a design point of view) to have the image number and some image description underneath the image and they should (of course) as well change when somebody clicks to the image.
here is the script I used so far for having the image change. can somebody quickly help me with the text changing? ideally, it would get the text out of a list of string variables I define or it could also work to read the text from an external TXT file etc.
here is the code I use so far!
<div id="content">
<img src= "testbild01.jpg" width="100%" height="auto" style="float:left" id="imageisabutton" />
<script type="text/javascript">
var images = ['testbild01.jpg', 'testbild02.jpg', 'testbild02.jpg'],
i = 0;
// preload
for (var j=images.length; j--;) {
var img = new Image();
img.src = images[j];
}
// event handler
document.getElementById('imageisabutton').addEventListener('click', function() {
this.src = images[i >= images.length - 1 ? i = 0 : ++i];
}, false);
</script>
Add another array for description, such as
var descriptions = ['description 1', 'description 2', 'description 3'],
Add a new element for the description, below the image, such as
<div id="mydescription"></div>
Add the following code after this.src = ...
document.getElementById('mydescription').innerHTML = i + ' ' + descriptions[i];
like this it works! thx
<div id="content">
<center>
<c id='numbers'>image 1/3</c>
<br />
<img src= "testbild01.jpg" width="100%" height="auto" style="float:left" id="myButton" />
<script type="text/javascript">
var images = [
'testbild01.jpg',
'testbild02.jpg',
'testbild03.jpg'
],
i = 0;
var mydescriptions = [
'text 1,
'text 2,
'text 2'
],
i = 0;
// preload
for (var j=images.length; j--;) {
var img = new Image();
img.src = images[j];
}
// event handler
document.getElementById('myButton').addEventListener('click', function() {
this.src =
images[i >= images.length - 1 ? i = 0 : ++i];
document.getElementById('mydescriptions').innerHTML = mydescriptions[i];
document.getElementById('numbers').innerHTML = 'image ' + (i+1) + '/' + (j+4);
}, false);
</script>
<br />
<c id='mydescriptions'>click image to move through slideshow</c>
</center>
Related
Images randomize successfully on button click but sounds will not play. I don't know what is wrong with the audio JS but it been perplexing me. I would like to get both to randomly execute while clicking the same button. I am using Chrome to test my work.
<script type = "text/javascript">
//Create random picture array
function imgchange() {
var myImages1 = new Array();
myImages1[1] = "Matthew1.jpg";
myImages1[2] = "Matthew2.jpg";
myImages1[3] = "Matthew3.jpg";
myImages1[4] = "Matthew4.jpg"; //Image Array
myImages1[5] = "Matthew5.jpg";
myImages1[6] = "Matthew6.jpg";
myImages1[7] = "Matthew7.jpg";
var rnd = Math.floor(Math.random() * myImages1.length);// Random Choice of Image
if (rnd == 0) {
rnd = 1;
}
document.getElementById("gen-img").src = myImages1[rnd];//Gets Image
}
function playRandomSound() {
//An array to house all of the URLs of your sounds
var sounds = new Audio["sound1.mp3", "sound2.mp3", "sound3.mp3", "sound4.mp3"];
//This line will select a random sound to play out of your provided URLS
var soundFile = sounds[Math.floor(Math.random() * sounds.length)];
//Find the player element that you created and generate an embed file to play the sound within it
document.getElementById("Button").innerHTML = "<embed src=\"" + soundfile + "\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
</script>
<body style="height: 663px">
<div class="Title" id="title">Alright! Alright! Alright!</div>
<p><img id="gen-img" src="img/who/1.jpg"></p>
<p> <input id="Button" type="button" value="Random" onclick="imgchange(); playRandomSound();"/></p>
</body>
You'll have to create an array of sounds like so:
var sounds = ["sound1.mp3", "sound2.mp3", "sound3.mp3", "sound4.mp3"].map(
(sound) => new Audio(sound)
);
You also have a typo in the line starting with document.getElementById("Button").innerHTML, soundFile has a capital F. Although I don't think you need that line, you can play the sound by calling play() on it, like soundFile.play(), please check the snippet below:
//Create random picture array
function imgchange() {
var myImages1 = new Array();
myImages1[1] = "Matthew1.jpg";
myImages1[2] = "Matthew2.jpg";
myImages1[3] = "Matthew3.jpg";
myImages1[4] = "Matthew4.jpg"; //Image Array
myImages1[5] = "Matthew5.jpg";
myImages1[6] = "Matthew6.jpg";
myImages1[7] = "Matthew7.jpg";
var rnd = Math.floor(Math.random() * myImages1.length); // Random Choice of Image
if (rnd == 0) {
rnd = 1;
}
document.getElementById("gen-img").src = myImages1[rnd]; //Gets Image
}
function playRandomSound() {
//An array to house all of the URLs of your sounds
var sounds = [
new Audio(
"https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3"
),
];
// var sounds = new Audio([
// ("sound1.mp3", "sound2.mp3", "sound3.mp3", "sound4.mp3")
// ]();
//This line will select a random sound to play out of your provided URLS
var soundFile = sounds[Math.floor(Math.random() * sounds.length)];
soundFile.play()
//Find the player element that you created and generate an embed file to play the sound within it
document.getElementById("Button").innerHTML =
'<embed src="' +
soundFile +
'" hidden="true" autostart="true" loop="false" />';
}
<div class="Title" id="title">Alright! Alright! Alright!</div>
<p><img id="gen-img" src="img/who/1.jpg" /></p>
<p>
<input id="Button" type="button" value="Random" onclick="imgchange(); playRandomSound();" />
</p>
I have multiple buttons (with the ids 'a', 'b', ...) and if you click them, they should display their corresponding image ('a.JPG', 'b.JPG', ...) at a fixed point on the website.
The idea is to listen for when a button is clicked and change the code inside the output to include its id.
'use strict';
var bild = '', i, j, k;
function gedrueckt(k) {
bild = '<img src="img/' + k + '.JPG" width="1600" hight="900" alt="Vergroessertes Bild"></img>';
document.querySelector('output').innerHTML = bild;
}
for (i = 1; i < 8; i = i + 1) {
j = String.fromCharCode(97 + i);
document.getElementById(j).addEventListener('click', gedrueckt(j));
}
The problem is that an image already appears before any button is clicked and pressing a different button does not change the displayed image.
This code should change the src on each button click, changing the picture according the the ID of the button:
let img = document.getElementById('img')
const change = id => {
img.src = `${id}.jpeg`
img.alt = `${id}.jpeg`
}
<img id="img" src="">
<br>
<button onclick="change(this.id)" id="a">A</button>
<button onclick="change(this.id)" id="b">B</button>
<button onclick="change(this.id)" id="c">C</button>
If there no src and no alt property provided, the image will not be displayed.
I might've misunderstood you, in that you want the image to change on keyboard button press, which this code should do the trick:
let img = document.getElementById('img')
const change = id => {
img.src = `${id}.jpeg`
img.alt = `${id}.jpeg`
}
const list = ['a','b','c']
document.addEventListener('keydown', e => list.includes(e.key) && change(e.key))
<img id="img" src="">
Get all the buttons and attach an click listener to it. Create img element on button click and append it to the element with id output.
const buttons = document.querySelectorAll('button')
const output = document.querySelector('#output');
buttons.forEach((button) => {
button.addEventListener('click', function() {
const img = document.createElement('img');
img.src = this.id + '.jpg';
output.innerHTML = "";
output.appendChild(img);
});
});
<button id="a">one</button>
<button id="b">two</button>
<button id="c">three</button>
<div id="output"></div>
My goal is to randomly change an image by clicking on a button. I have found a snippet that does that but I wanted to train my skills and work my way through it, this is what I got so far:
When I click the button, with the variable on line 11, nothing happens, but when I put the URL instead of the variable (copied from the console from line 22), it goes to the according picture. I don't get it...
When my "imageCount" is full, I get an error
var imageCount = [];
var image = ["img/01.jpg", "img/02.jpg", "img/03.jpeg", "img/04.jpeg"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "\"url('" + image[rand] + "')\""
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
} else if (imageCount.length === image.length) {
imageCount = 0;
} else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
<link href="./style/main.css" rel="stylesheet">
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>
Two things stop your demo code from working:
#imageWrapper has no height, so the image is not displayed (probably only because your page's CSS is missing)
You reset the imageCount variable to 0 instead of []
var imageCount = [];
var image = ["//baconmockup.com/300/199/", "//baconmockup.com/300/200/", "//baconmockup.com/300/201/", "//baconmockup.com/300/202/"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "url('" + image[rand] + "')"
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
}
else if (imageCount.length === image.length) {
imageCount = [];
}
else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
#imageWrapper {
height: 200px;
outline: solid black 1px;
}
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>
<script type=text/javascript>
var topLeftImages = ["op.jpg", "qa.jpg", "fl.jpg", "eatgr.jpg", "na.jpg", "ctcc.jpg", "na.jpg", "oacahu.jpg", "hc.jpg", "sup.jpg", "oa.jpg", "rffcc.jpg"];
var topRightImages = ["eatgr.jpg", "ulandscaping.jpg", "fp.jpg", "clf.jpg", "lss.jpg", "sup.jpg", "ulandlord.jpg", "lqbc.jpg", "lss.jpg", "lp.jpg", "ulandlord.jpg", "qa.jpg"];
var bottomLeftImages = ["poss.jpg", "un.jpg", "pocsik.jpg", "sep.jpg", "rms.jpg", "fp.jpg", "al.jpg", "un.jpg", "sep.jpg", "op.jpg", "al.jpg", "oacahu.jpg"];
var bottomRightImages = ["nup.jpg", "clf.jpg", "rffcc.jpg", "sla.jpg", "lqbc.jpg", "pocsik.jpg", "fp.jpg", "np.jpg", "lwtgr.jpg", "lqbc.jpg", "lcsik.jpg", "poss.jpg"];
for(var i = 0, l = topLeftImages.length; i < l; i++)
{
setTimeout(function()
{
document.getElementById('myimage1').src = "images\\" + "op.jpg";
document.getElementById('myimage2').src = "images\\" + topRightImages[i];
document.getElementById('myimage3').src = "images\\" + bottomLeftImages[i];
document.getElementById('myimage4').src = "images\\" + bottomRightImages[i];
}, 10000);
}
</script>
Associated HTML:
<img id="myimage1" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
<img id="myimage2" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
<img id="myimage3" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
<img id="myimage4" src="http://www.hdwallpapers.in/walls/apple_sky_blue_aurora-wide.jpg" width="400" />
This code is meant to show four images, and every 10 seconds, switch all four images simultaneously, going through all of my images in my four arrays. The images are in the images/ directory above my HTML file that contains this code. For testing purposes, I changed myimage1 to change to op.jpg only. This works and correctly shows op.jpg. However, when querying the arrays, instead of the file names, I get undefined. That is problem number one.
Problem number two, when I change my for loop to a more normal looking one like:
for(var i = 0; i < l2; i++)
The script stops working entirely (doesn't show op.jpg and doesn't even try to change the images)... what the hell!
I'm using Firefox and Google Chrome for testing purposes.
I suggest something like that instead:
<script type=text/javascript>
$(document).ready(function () {
var topLeftImages = ["op.jpg", "qa.jpg", "fl.jpg", "eatgr.jpg", "na.jpg", "ctcc.jpg", "na.jpg", "oacahu.jpg", "hc.jpg", "sup.jpg", "oa.jpg", "rffcc.jpg"];
var topRightImages = ["eatgr.jpg", "ulandscaping.jpg", "fp.jpg", "clf.jpg", "lss.jpg", "sup.jpg", "ulandlord.jpg", "lqbc.jpg", "lss.jpg", "lp.jpg", "ulandlord.jpg", "qa.jpg"];
var bottomLeftImages = ["poss.jpg", "un.jpg", "pocsik.jpg", "sep.jpg", "rms.jpg", "fp.jpg", "al.jpg", "un.jpg", "sep.jpg", "op.jpg", "al.jpg", "oacahu.jpg"];
var bottomRightImages = ["nup.jpg", "clf.jpg", "rffcc.jpg", "sla.jpg", "lqbc.jpg", "pocsik.jpg", "fp.jpg", "np.jpg", "lwtgr.jpg", "lqbc.jpg", "lcsik.jpg", "poss.jpg"];
var i = 0;
var max = 12;
setInterval(function()
{
var index = i % max;
document.getElementById('myimage1').src = "images\\" + topLeftImages[index];
document.getElementById('myimage2').src = "images\\" + topRightImages[index];
document.getElementById('myimage3').src = "images\\" + bottomLeftImages[index];
document.getElementById('myimage4').src = "images\\" + bottomRightImages[index];
i++;
}, 10000);
});
</script>
jsFiddle with some example images http://jsfiddle.net/ApfJz/8/
I'm trying to get Fancybox (http://fancybox.net/howto) to work for the dailyimg div (see the HTML snippet below) to enlarge the image. The div contains a single image that is rotated daily (see the JavaScript that follows). I'm not sure how to get the Fancybox working. Any help would be much appreciated. -M
<div id="emma2011_left">
<h2>Image of the Day</h2>
<div id="dImg">
<a id="inline" href="#dailyimg"><div id="dailyimg" class="feature"></div></a>
<div id="title" class="feature"></div>
<div id="caption" class="feature"></div>
</div>
</div>
<script type="text/javascript">
oImages = [
{time: '2011-8-28', img: 'images/rotation_pics/test_pic.jpg', title: "testpic title", caption: "my caption" },
time: '2011-8-29', img: 'images/rotation_pics/test_pic2.jpg', title: "testpic title", caption: "my caption" }
];
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var today = year + "-" + month + "-" + day;
window.onload = function(){
for(var i in oImages){
if(oImages[i].time == today) oTodayImage = oImages[i];
}
oImg = document.createElement("img");
oImg.setAttribute("title", oTodayImage.title);
oImg.setAttribute("src", oTodayImage.img);
var e = document.getElementById("dailyimg");
e.appendChild(oImg);
var title=document.createTextNode(oTodayImage.title);
var f = document.getElementById("title");
f.appendChild(title);
var capt=document.createTextNode(oTodayImage.caption);
var g = document.getElementById("caption");
g.appendChild(capt);
$("a#inline").fancybox({
'overlayShow': false,
'transitionIn' : 'elastic',
'transitionOut' : 'elastic'
});
};
</script>
Only basic debugging is required to fix this problem. If you use Internet Explorer you can press F12 and then the "Console" tab to see javascript errors. If you use Firefox install the "Firebug" add-on and click the little bug icon to get started.
The 13th line of code is missing a brace - put it in front of the second array element just before the word "time:" like "{time:".
The last line of code before the </script> tag has an extra semi-colon and should be "}" instead of "};".
Later: Full code added below. I recommend trying to get this working using the exact syntax and file versions below, only then should you try to incorporate into your code. Sorry about the HTML formatting, best I could do in the stackoverflow editor. For the sample your root folder (2 files, 1 folder) for the sample should have three items in it and look like this:
/default.htm
/jquery-1.4.4.min.js
/fancybox/[all the remaining files should be in this folder]
<html><head>
<script src="jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript" src="fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<link rel="stylesheet" type="text/css" href="fancybox/jquery.fancybox-1.3.4.css" />
<script type="text/javascript">
oImages = [{ time: '2011-8-28', img: 'images/rotation_pics/test_pic.jpg', title: "testpic title", caption: "my caption" }, { time: '2011-8-29', img: 'images/rotation_pics/test_pic2.jpg', title: "testpic title", caption: "my caption" }
];
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var today = year + "-" + month + "-" + day;
window.onload = function () {
for (var i in oImages) {
if (oImages[i].time == today) oTodayImage = oImages[i];
}
oImg = document.createElement("img");
oImg.setAttribute("title", oTodayImage.title);
oImg.setAttribute("src", oTodayImage.img);
var e = document.getElementById("dailyimg");
e.appendChild(oImg);
var title = document.createTextNode(oTodayImage.title);
var f = document.getElementById("title");
f.appendChild(title);
var capt = document.createTextNode(oTodayImage.caption);
var g = document.getElementById("caption");
g.appendChild(capt);
$("a#inline").fancybox({
'overlayShow': false,
'transitionIn': 'elastic',
'transitionOut': 'elastic'
});
}
</script>
</head>
<body>
<div id="emma2011_left">
<h2>
Image of the Day</h2>
<div id="dImg">
<a id="inline" href="#dailyimg">
<div id="dailyimg" class="feature">
</div>
</a>
<div id="title" class="feature">
</div>
<div id="caption" class="feature">
</div>
</div>
</div>
</body>
</html>