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>
Related
<!DOCTYPE html>
<html>
<body>
<p id="Image"></p>
Basically what im tryijngto do s
One fix I'd recommend would be splitting your logic into two functions, one the user clicks to check their answer, and one they click to see the next question. This will allow you to display the congrats message on the screen rather than in an alert. Here is that in action:
let score = 0;
let questionsAsked = 0;
const button = document.querySelector('button');
const input = document.getElementById('userInput');
const gameScore = document.getElementById('game-score-inner');
gameScore.add = (pts = 1) => gameScore.innerHTML = parseInt(gameScore.textContent) + 1;
gameScore.subtract = (pts = 1) => gameScore.innerHTML = Math.max(parseInt(gameScore.textContent) - 1, 0);
const checkMessage = document.getElementById('check-message');
checkMessage.set = message => checkMessage.innerHTML = message;
checkMessage.clear = message => checkMessage.innerHTML = '';
const options = {
chad: 'https://via.placeholder.com/600x400/000000/efebe9/?text=Chad',
bob: 'https://via.placeholder.com/600x400/000000/efebe9/?text=Bob',
john: 'https://via.placeholder.com/600x400/000000/efebe9/?text=John'
}
function askQuestion() {
checkMessage.clear();
input.value = '';
const optionsNames = Object.values(options);
const randomPhoto = optionsNames[Math.floor(Math.random() * optionsNames.length)];
document.getElementById('image').innerHTML = `<img src="${randomPhoto}" id="question-image" width="250" height="250" />`;
button.setAttribute('onclick','checkAnswer()');
button.textContent = 'Check Your Answer!';
}
function checkAnswer() {
const userGuess = options[input.value.toLowerCase()];
const correctAnswer = document.getElementById('question-image').getAttribute('src');
if (options[input.value.toLowerCase()] === correctAnswer) {
checkMessage.set('CONGRATULATIONS!!! YOU GUESSED IT RIGHT');
gameScore.add();
} else {
checkMessage.set('SORRY, IT WAS INCORRECT');
gameScore.subtract();
}
questionsAsked++;
button.setAttribute('onclick','askQuestion()');
button.textContent = 'Next Question';
}
askQuestion();
<p id="image"></p>
<p id="game-score">Score: <span id="game-score-inner">0</span></p>
<button onclick="checkAnswer()">Start Game!</button>
<input id="userInput" type="text" />
<p id="check-message"></p>
If you would prefer to keep everything in one function and use alerts for the congrats message, you can do so by keeping track of then number of questions asked, and not instantly checking the answer on the first load, like this:
let score = 0;
let questionsAnswered = -1;
const imageContainer = document.getElementById('image');
const button = document.querySelector('button');
const input = document.getElementById('user-input');
const gameScore = document.getElementById('game-score-inner');
gameScore.add = (pts = 1) => gameScore.innerHTML = parseInt(gameScore.textContent) + 1;
gameScore.subtract = (pts = 1) => gameScore.innerHTML = Math.max(parseInt(gameScore.textContent) - 1, 0);
const options = {
chad: 'https://via.placeholder.com/250x250/000000/efebe9/?text=Chad',
bob: 'https://via.placeholder.com/250x250/000000/efebe9/?text=Bob',
john: 'https://via.placeholder.com/250x250/000000/efebe9/?text=John'
}
function askQuestion() {
questionsAnswered++;
const optionsNames = Object.values(options);
const randomPhoto = optionsNames[Math.floor(Math.random() * optionsNames.length)];
if (questionsAnswered) {
const userGuess = options[input.value.toLowerCase()];
const correctAnswer = document.getElementById('question-image').getAttribute('src');
if (options[input.value.toLowerCase()] === correctAnswer) {
gameScore.add();
alert('CONGRATULATIONS!!! YOU GUESSED IT RIGHT');
} else {
gameScore.subtract();
alert('SORRY, IT WAS INCORRECT');
}
questionsAnswered++;
}
imageContainer.innerHTML = `<img src="${randomPhoto}" id="question-image" width="250" height="250" />`;
input.value = '';
}
askQuestion();
<p id="image"></p>
<p id="game-score">Score: <span id="game-score-inner">0</span></p>
<button onclick="askQuestion()">Check Answer!</button>
<input id="user-input" type="text" />
Both solutions would work fine with alerts, though the first solution offers some greater flexibility for any functions you make want to perform in between questions. One other main fix there was to make here was to check change the image after checking the answer, and also making sure to actually fun the function in the beginning using askQuestion() in this case. I also added a couple of handy functions gameScore.add() and gameScore.subtract() to ease future use.
You can pass in other integers such as gameScore.add(2) if you every wanted to have double-weighted questions. I also added a Math.max() line to ensure the score never passes below 0. You can remove this if you would like the player's score to pass into negative numbers.
Here is a working version of your game. To begin: <br>
1.Your code was not modifying the src of the image (thus no image appears) <br>
1a. I am modifying the src attribute associated with the `img` tag now. <br>
1b. `document.getElementById("Image").src = randomPhoto;` <br>
2. `theArrayArray` does not exist. I updated the variable to `theArray` <br>
3. To display an image when the game begins you need a handler. <br>
3a. I added the `button` to handle that <br>
4. Unless you want the user to type out `.jpg` you need to remove .jpg <br>
4a. `randomPhoto = randomPhoto.replace(".jpg", "");` <br>
<img id="Image" src="#" width="250" height="250">
<br>
<br>
<input id="userInput" type="text">
<br>
<br>
<button type="button" id="btn" onclick="startGame()">Start Game</button>
<span id="GameScore">Score:</span>
<script>
let score = 10;
var Chad = "Chad.jpg";
let begin = 1;
let thePhoto;
var someArray = [ Chad, Bob
];
function startGame() {
if (start == 0) {
for (var l = 2; i < 3; i--) {
randomPhoto = theArray[Math.floor(Math.random()*theArray.length)];
document.getElementById("Image").src = randomPhoto;
document.getElementById("btn").innerHTML = "Submit";
start = 1;
}
} else {
randomPhoto = randomPhoto.replace(".jpg", "Insert");
}
else {
for (var x = 0; i < 3; i++) {
TheName = theArray[Math.floor(Math.random()*theArray.length)];
document.getElementById("Image").src = theName;
alert("No");
scorex = score-1;
}
document.getElementById("theScore").innerHTML="Score: "+score;
</script>
</body>
</html>
i want to increment index number of the image to actually get the size of the current image each time i click the button here is the code:
var next = document.querySelector("#nextBtn");
var prev = document.querySelector("#prevBtn");
var imgContainer = document.querySelector(".imgContainer");
let img = document.querySelectorAll(".imgContainer > img");
i want this var imgIndex = 0; to increment and store the new value which is incremented.
let size = img[imgIndex].clientWidth;
next.addEventListener('click', slideImg);
function slideImg() {
imgContainer.style.transform = "translateX(" + (-size) + "px)";
imgIndex++;
}
Refer this code.
You may not used the image index top of your function / global value. That's what it is again starts from zero.
function slideImg() {
var next = document.querySelector("#nextBtn");
var prev = document.querySelector("#prevBtn");
next.addEventListener('click', slideImg1);
}
var imgIndex = 0;
function slideImg1() {
var imgContainer = document.querySelector(".imgContainer");
let img = document.querySelectorAll(".imgContainer > img");
let size = img[imgIndex].clientWidth;
alert(imgIndex);
img[imgIndex].style.transform = "translateX(" + (-size) + "px)";
imgIndex++;
}
</script>
<body onload="slideImg()">
<input type="button" id="nextBtn" value="+" />
<input type="button" id="prevBtn" value="+" />
<div class="imgContainer">
<img src="file" />
<img src="file" />
</div>
</body>
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>
Here is the link to the jsbin.
I was almost finished with my project (I thought I was) and then I tested it out. It is supposed to add buttons with the chosen title of the task and the number of points it awards. Every time the button is clicked the points would be added on to the "Points" section and every 500 points my "Level" would increase.
Upon finishing it, it worked. Then I went to clear the localStorage since that's what I used to save the information, but I wanted to start over. When I did that, the 'Points' section, or 'results' value, keeps returning as "NaN". The code is exactly the same as it was when it worked. Can someone please tell me how to fix this problem, thank you in advance.
Here is the code. (Used bootstrap for CSS)
HTML
<center>
<br>
<h2> Add task </h2>
<div class='well' style='width:500px' id="addc">
<div id="addc">
<input class='form-control' style='width:450px' id="btnName" type="text" placeholder="New Task" /><br>
<input class='form-control' style='width:450px' id="btnPoints" type="text" placeholder="Points" /><br>
<button id="addBtn">Add</button>
</div> </div>
<div class='well' style='width:230px' id="container">
</div>
<hr style="width:400px;">
<h3>Points </h3>
<div id="result">0</div>
</div>
<hr style="width:400px;">
<div style="width:400px;">
<h3>Level
<p id='lvl'>0</p>
</div>
<hr style="width:400px;">
</center>
JavaScript
var res = document.getElementById('result');
res.innerText = localStorage.getItem('myResult');
var level = document.getElementById('lvl');
level.textContent = localStorage.getItem('myLevel');
var btns = document.querySelectorAll('.btn');
for(var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
}
var addBtn = document.getElementById('addBtn');
addBtn.className = "btn btn-default";
addBtn.addEventListener('click', function() {
var container = document.getElementById('container');
var btnName = document.getElementById('btnName').value;
var btnPoints = parseInt(document.getElementById('btnPoints').value);
if(!btnName)
btnName = "Button ?";
if(!btnPoints)
btnPoints = 50;
var newBtn = document.createElement('button');
var newPnt = document.createElement('span');
newBtn.className = 'btn btn-danger';
newBtn.innerText = btnName;
newBtn.setAttribute('data-points', btnPoints);
newBtn.addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
newPnt.className = 'label';
newPnt.innerText = "+" + btnPoints;
container.appendChild(newBtn);
container.appendChild(newPnt);
});
function addToResult(pts) {
var result = document.getElementById('result');
result.innerText = parseInt(result.innerText) + parseInt(pts);
var lvl = 0;
var a = 100;
while (result.innerText > 5*a) {
lvl+=1;
a+=100;
}
document.getElementById('lvl').innerText = lvl;
var res = document.getElementById('result');
localStorage.setItem("myResult", res.innerText);
var level = document.getElementById('lvl');
localStorage.setItem("myLevel", level.textContent);
}
You were parsing result.innerText as a number, but its value, initially, was actually either NaN or nothing, both which end up being NaN. One fix is to just check if it parsed to a number, and if it didn't, fall back to 0.
I just basically changed that and removed some getElementByIds that, in my opinion, were redundant, check the addToResult function:
http://jsfiddle.net/owc26a0p/1/
function addToResult(pts) {
// NaN is falsy, so you can just use || to make a fallback to 0
var result = parseInt(resDiv.innerText, 10) || 0,
lvl = 0,
a = 100;
result = result + parseInt(pts, 10) || 0;
while (result > 5 * a) {
lvl += 1;
a += 100;
}
resDiv.innerText = result;
levelDiv.innerText = lvl;
localStorage.setItem("myResult", result);
localStorage.setItem("myLevel", levelDiv.textContent);
}
I ended up using jsFiddle since I couldn't always get jsBin to save my changes. Good luck.
I have a script which toggles block/none display of a div, onClick. The onClick also toggles an associated "thumbnail" image from active to inactive.
Only in Firefox, the div's stack on top of each other. It seems as if the onClick is not associating the display:none style with the current item.
I made sure that all divs have associated ID's which seems to be the top questions related to getElementById issues in Firefox.
Any thoughts on troubleshooting this would be helpful, thank you!
Here is my javascript:
var curVid = "VideoA";
var curImg = "VideoA_thumbnail";
function changeVideo(id, img)
{
if(document.getElementById(id) != null && curVid != id)
{
document.getElementById(curVid).style.display = "none";
document.getElementById(id).style.display = "block";
document.getElementById(id + "_thumb").src = "..//Thumbnails//" + img + "_selected.jpg";
document.getElementById(id + "_thumb").style.cursor = "default";
document.getElementById(curVid + "_thumb").src = "..//Thumbnails//" + curImg + ".jpg";
document.getElementById(curVid + "_thumb").style.cursor = "pointer";
if(VideoJS.browserSupportsVideo())
{
document.getElementById(curVid + "_video").pause();
document.getElementById(curVid + "_video").currentTime = 0;
VideoJS.setup(id + "_video");
document.getElementById(id + "_video").play();
}
else
{
$f(curVid + "_flash").stop();
$f(id + "_flash").play();
}
curVid = id;
curImg = img;
}
}
and this is the HTML
<div id = "VideoA" style = "display:block;">content here</div>
<div id = "VideoB" style = "display:none;">content here</div>
<div id = "VideoC" style = "display:none;">content here</div>
<div id = "VideoD" style = "display:none;">content here</div>
<div id = "VideoE" style = "display:none;">content here</div>
<div>
<img src = "a.jpg" id = "VideoA_thumb" onclick = "changeVideo('VideoA', 'VideoA_thumb')" />
<img src = "b.jpg" id = "VideoB_thumb" onclick = "changeVideo('VideoB', 'VideoB_thumb')" />
<img src = "c.jpg" id = "VideoC_thumb" onclick = "changeVideo('VideoC', 'VideoC_thumb')" />
<img src = "d.jpg" id = "VideoD_thumb" onclick = "changeVideo('VideoD', 'VideoD_thumb')" />
<img src = "e.jpg" id = "VideoE_thumb" onclick = "changeVideo('VideoE', 'VideoE_thumb')" />
</div>