JavaScript Display Image and Text Rather than Alert Message - javascript

I'm a newbie and starting to learn coding. I have a question regarding the famous "How many fingers am I holding up?" project. So instead of an alert message, I want the actual image of a finger with 1-5 and the message of either it is correct or not.
I think there are jquery codes.. but i don't want to jump to jquery and learn hardcore javascript first. I'm stuck with creating image Arrays and cannot manage to make the image come up.
Here's the code I have:
<body>
<p>How many fingers am I holding up?</p>
<p><input type="text" id="guess"> <button id="checkGuess">Guess!</button></p>
<div id="image"></div>
<div id="text"></div>
<script type="text/javascript">
var imgArray = new Array();
imgArray[1] = new Image();
imgArray[1].src="images/1.png";
imgArray[2] = new Image();
imgArray[2].src="images/2.png";
imgArray[3] = new Image();
imgArray[3].src="images/3.png";
imgArray[4] = new Image();
imgArray[4].src="images/4.png";
imgArray[5] = new Image();
imgArray[5].src="images/5.png";
document.getElementById("checkGuess").onclick = function() {
var randomNumber = Math.random();
randomNumber = randomNumber * 6;
randomNumber = Math.floor(randomNumber);
if (document.getElementById("guess").value == randomNumber) {
doument.getElementById("image").innerHTML = imgArray[num] + alert("Well done! You got it!");
} else {
alert("Nope! The number was " + randomNumber);
}
}
</script>
</body>
Thanks Guys! Appreciate your help!
Cheers!
Char

I think you can do something like this fiddle.
https://jsfiddle.net/6a4p2po4/5/
What I did was to make the imgArray an array of src of images, and updated the img src depending on the result.
I noticed while working you have some typos and unset variables.
For example, "doument" is misspelled, and "'num'" is not set.
doument.getElementById("image").innerHTML = imgArray[num] + alert("Well done! You got it!");
It might help to use Chrome or another browser to check the console (F12). It will definitely help you debug.
Using console.log() instead of alert() will make it show up as a log instead of a pop up window, so you can check the values that you stored on variables, i.e. console.log(randomNumber);

You're on the right track! Good job so far!
You said
So instead of an alert message, I want the actual image of a finger...
which leads me to think that we never want to call alert() and instead want to display an image and a message. Assuming I am correct in my supposition, here is some code...
<html>
<head>
<!-- some other stuff... -->
<!-- CSS is your friend! -->
<style>
.hidden {
display: none;
}
</style>
</head>
<body>
<p>How many fingers am I holding up?</p>
<p>
<input type="text" id="guess">
<button id="checkGuess" onclick="checkGuess()">Guess!</button>
</p>
<div id="image">
<!-- We can put the images in here then just hide/show them, which is much easier! -->
<img class="hidden" src="./images/1.png"/>
<img class="hidden" src="./images/2.png"/>
<img class="hidden" src="./images/3.png"/>
<img class="hidden" src="./images/4.png"/>
<img class="hidden" src="./images/5.png"/>
</div>
<div id="text"></div>
<script>
function checkGuess(){
var actualFingerCount = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
//the `+` casts the value into a number
var userGuess = +document.getElementById('guess').value;
//get all of our images
var images = document.querySelectorAll('img');
//hide all of them just to be safe
images.forEach(function(img){
img.classList.add('hidden');
});
//then show the one we want
images[actualFingerCount - 1].classList.remove('hidden');
var textDiv = document.getElementById('text');
if(actualFingerCount === userGuess) {
textDiv.innerHTML = 'Yay, you got it!';
}
else {
textDiv.innerHTML = 'Whoops, try again! The number was ' + actualFingerCount + '.';
}
}
</script>
</body>
</html>
And there you have it!
Notice that this is a contrived example. In the real world, you should never define functions in the global namespace, nor should you rely on elements being in a certain order, like I did with the images. Maybe you can take it and improve it to follow better coding standards!

Related

Loading an img object with a src in javascript

I want to add a thumbnail picture to a book's details, derived from the google books api, on the webpage. The code below will place the source code (api) for the appropriate book, first into the text field bookCover and then into the var copyPic, and then it should be copied into imgDisp, but it doesn’t. I can see that bookCover holds the right text, and have checked that copyPic holds the correct content.
<img id="imgDisp" src="http://books.google.com/books/content?
id=YIx0ngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api" width="85" height="110"" />
$.getJSON(googleAPI, function(response) {
$("#title").html(response.items[0].volumeInfo.title);
$("#subtitle").html(response.items[0].volumeInfo.subtitle);
$("#author").html(response.items[0].volumeInfo.authors[0]);
$("#description").html(response.items[0].volumeInfo.description);
$("#version").html(response.items[0].volumeInfo.contentVersion);
$("#modeR").html(response.items[0].volumeInfo.readingModes.text);
$("#bookCover").html(response.items[0].volumeInfo.imageLinks.thumbnail);
var copyPic = document.getElementById('bookCover').innerHTML;
document.getElementById("imgDisp").src=copyPic;
Does anyone know why not? Or can I put the api details directly into imgDisp (can’t find such code syntax anywhere on the net)? Everything else is working fine. If I put a src in directly, then it works e.g.
document.getElementById("imgDisp").src = “http://.....api”
but not with a variable.
Without more info - eg, I can't see where the getJSON() function ends or what the URL's are, I can't see what the issue may be (except, perhaps, as in my last comment).
I idea seems ok, as I can replicate it (in a cut-down version of course):
function copyImageSource() {
let d = document.getElementById("bookCover").innerHTML;
document.getElementById("imgDisp").src = d;
}
<button onclick="copyImageSource();">Get image</button>
<div id="bookCover">https://duckduckgo.com/assets/icons/meta/DDG-icon_256x256.png</div>
<img id="imgDisp" src="">
I assume that this is the sort of thing you are trying to achieve?
(javascript -> jquery:
let copyPic = $("#bookCover").html();
$("#imgDisp").attr("src", copyPic);
)
Version using jquery:
function copyImageSource() {
let d = $("#bookCover");
d.html("http://books.google.com/books/content?id=YIx0ngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api");
let dCopy = d.html().replace(/&/g, "&");
$("#imgDisp").attr("src", dCopy);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="copyImageSource();">Get image</button>
<div id="bookCover"></div>
<img id="imgDisp" src="https://www.picsearch.com/images/logo.png"/>
If you have jQuery you can easily do the following:
let source = 'https://img.com/image.png';
//to get the image object that has the above just do this:
let img = $('img[src="' + source + '"]');

Javascript move picture to the right where the first goes to the back comes to the front with the click of a button

I am trying to create a JavaScript code that has 3 images up when a button is pushed it looks like they are all moving right. So far I am super lose on the JavaScript part of the code. I can't get it to move, or the button to work.
HTML:
<head>
<script src="switchright.js"> </script>
<body>
<h1 style="text-align:center">Image Switcher</h1>
<center>
<img src="../images/smile.png" id=smile>
<img src="../images/plain.png" id=plain>
<img src="../images/wink.png" id=wink>
<br>
<button type="button" id=theButton>Switch Right</button>
</center>
</body>
</head>
Javascript:
theButton.onclick = function pictureChange(){
document.getElementById('smile').src="../images/wink.png";
}
theButton.onclick = function pictureChange(){
document.getElementById('plain').src="../images/smile.png";
}
theButton.onclick = function pictureChange(){
document.getElementById('wink').src="../images/smile.png";
}
As I understood - you have 3 images in a row and you want to change their sources circularly by clicking the button.
Hope this helps ( by the way - I think you should embrace the value of id attribute in double quotes )
// this will iterate from 0 to 2 and represents
// the current position of wink
var position = 0;
// save the links to files in an array
var images = ["../images/wink.png", "../images/smile.png", "../images/smile.png"];
// document.getElementById() are expensive in time
// so better to save the references to the objects
// and not find them every click
var smile = document.getElementById('smile');
var plain = document.getElementById('plain');
var wink = document.getElementById('wink');
theButton.onclick = function() {
// here you now depend on the position values that
smile.src = images[position % 3];
plain.src = images[(position + 1) % 3];
wink.src = images[(position + 2) % 3];
// increments the position variable and checks
// that it deosn't become beggier that 2
position++;
if (position > 2) {
position = 0;
}
}
Please mind that you can change the sources in the images array ( if there would be some issues with that ).
Switch the sources in just one function like this:
window.slide = function(){
var store = document.getElementById('wink').src;
document.getElementById('wink').src = document.getElementById('plain').src;
document.getElementById('plain').src = document.getElementById('smile').src;
document.getElementById('smile').src = store;
}
.small {
width: 25px;
height: 25px;
}
<h1 style="text-align:center">Image Switcher</h1>
<center>
<img class="small" src="http://www.costarricense.cr/pagina/radiogigante/index_files/image007.gif" id="smile">
<img class="small" src="http://www.skip-hop.co.uk/images/skip-hop-number-2.gif" id="plain">
<img class="small" src="http://upload.wikimedia.org/wikipedia/commons/e/e7/L3lo.gif" id="wink">
<br>
<button type="button" onclick="slide()">Switch Right</button>
</center>

Uncaught TypeError: Cannot set property 'src' of null...Choose your own adventure

I'm just learning javascript and I'm having some trouble. I'm making a choose your own adventure game where you go through a maze. There are pictures showing you what is going on. The pictures will change after each decision you make. I have a problem changing the pictures after typing in left or right. I keep getting Uncaught TypeError: Cannot set property 'src' of null error messages every time it tries to load the picture. Java says that the problem is occuring at Line 66
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Brian.Bosco-Hazey Maze Adventure</title>
<script type="application/javascript">
var flag;
var output;
var name;
var n1 = "what is your name?"
var s1 = "You wake up in a spooky maze. You must find your way out or this place will become your grave. You can go <b>Left</b> or <b>Right</b>?";
var s2 = "You come across a wizard at a fork in the maze. He gives you a magic sword to defend yourself with. You can either go <b>Left</b> or <b>Right</b>?";
var e1 = "You encounter a monster. you attempt to escape, but it pounces on you and tears off your flesh. You have died. GAME OVER. Type restart to try again";
var e2 = "You come across a dead end, looks like you have to go back the way you came. When you turn around you step on a trap on the floor and the whole tunnel collapses on you. You did not survive. Please type restart to try again."
var e3 = "While walking down this long hallway, you come across a giant monster guarding the exit door. You take the sword the wizard gave you and you slay the beast. You go through the door and exit the maze. Congradulations you have beaten the game! Type restart to play again. ";
var done = "What are you doing? You are still dead. Type restart to start again";
var myImage;
var newImage;
function init(){
output = document.getElementById('output');
output.innerHTML="";
flag="n1";
texter(n1);
name = "";
document.body.style.background="white";
}
function texter(newText){
console.log(newText+" from texter");
var oldText = document.getElementById('output').innerHTML;
document.getElementById('output').innerHTML= newText;//+" "+oldText;
}
function Imger(newImage){
document.getElementById('img1').src = newImage;
document.getElementById('img2').src = newImage;
}
function game(){
var input = document.getElementById('input').value;
console.log("the input is "+input);
if(input=="restart"){
init();
}else{
if(flag=="n1"){
name = input;
flag="s1";
texter("hello "+name+" "+s1);
document.getElementById('img1').src = "hooded man.jpg";
output.style.color="blue";
}else if(flag=="s1"){
//ask c1
if(input=="right"){
flag="s2";
texter(s2);
document.body.style.background="green";
}else if(input=="left"){
texter(e1);
flag ="e1";
document.getElementById('img2').src = "last scene.jpg";
}else{
texter("error");
}
}else if(flag=="s2"){
//ask c2
if(input=="right"){
flag="e2";
texter(e2);
document.body.style.background="red";
}else if(input=="left"){
texter(e3);
flag ="e3";
document.body.style.background="yellow";
}else{
texter("error");
}
}else if(flag=="e1"){
//e1
texter(done);
}else if(flag=="e2"){
//e2
texter(done);
}else if(flag=="e3"){
//e3
texter(done);
}
}
}
</script>
</head>
<body onLoad="init()">
<img src="start.jpg" id="img1" width="500" height="500">
<p id="output">this is the start text</p>
<input type="text" id="input">
<input type="button" value="submit" onClick="game()" ">
</body>
</html>
document.getElementById('img2').src = newImage;
There is no id="img2" in the HTML, so document.getElementById('img2') == null.
May you can add one under img1:
<img src="start.jpg" id="img1" width="500" height="500">
<img src="start.jpg" id="img2" width="500" height="500">
OR you can remove the JS line:
document.getElementById('img2').src = newImage;
And also:
document.getElementById('img2').src = "last scene.jpg";
Or change it to:
document.getElementById('img1').src = "last scene.jpg";
I was had same problem and i just did like this and work:
function Imger(newImage){
document.getElementById('img1').src = newImage;
if(document.getElementById('img2') != NULL){
document.getElementById('img2').src = newImage;
}
}
just used if not NULL for it.
if(image != NULL){
image.src = 'image url';
}
although I won't be much help since this was asked 3 years ago by that script should actually be after the img and the img should be behind it and than it should possibly work. I would say that you have no id's of img2 but someone already pointed it out and if his suggestion doesn't work that do my suggestion.

Hide/show images button JS

I have a webpage where i have 3 images and I have a button to hide those images all at once on click, and then show them(this part is not implemented yet). I have a JS function for hiding them but it is not working and I have no idea why. So this is part of my code:
<div id="left"><img id="leftimage" name="leftimage" src="pic1url.jpg" style=
"visibility:visible"></div>
<div id="centerright">
<div id="center"><img id="centerimage" name="centerimage" src="pic2url.jpg"
style="visibility:visible"></div>
<div id="right"><img id="rightimage" name="rightimage" src="pic2url.jpg"
style="visibility:visible"></div>
</div><script type="text/javascript">
var hideShowButton = document.getELementById("hideShowButton");
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage"; center:"centerimage"; right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{ document.getElementById(allImages[image]).style.visibility = 'hidden';
document.getElementById(allImages[image+"1"]).style.visibility = 'hidden';
document.getElementById(allImages[image+"2"]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
</script>
<div id="buttons">
<input id="hideShowButton" type="button" value="Hide Pics">
</div>
Before reading the answer, I highly suggest you learn how to use the browser's console. It will print all the errors that make your JavaScript code to crash. I also suggest you take some time to read JavaScript tutorials :)
There are many things wrong with your code. First, there is a typo "getELementById" (L is uppercase instead of lowercase). Second, you need to place the script tags bellow your button. Third, when creating an object, you should separate it's properties using commas (,) not semicolons (;) . Finally, you made a false use of the for loop. Just to help you out, here is the corrected code but don't expect people to do that for you every time. You need to find mistakes like these on your own in the future :)
<div id="left">
<img src="pic1url.jpg" id="leftimage" style="visibility:visible" />
</div>
<div id="centerright">
<div id="center">
<img src="pic2url.jpg" id="centerimage" style="visibility:visible"/>
</div>
<div id="right">
<img src="pic2url.jpg" id="rightimage" style="visibility:visible"/>
</div>
</div>
<div id="buttons">
<input type="button" value="Hide Pics" id="hideShowButton" />
</div>
<script type="text/javascript">
var hideShowButton = document.getElementById("hideShowButton");
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage", center:"centerimage", right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{
document.getElementById(allImages[image]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
</script>
Use can use diplay none or block property of css to hide and show any view respectively
<img id="one" src="pic1url.jpg" style="display:none;" />
Through javascript you can use this
document.getElementById(one).style.display = 'none';
Sorry, but your code is a bit messy. Why are you using a for statement if then you try to hide every image every time?
By the way, you're misusing the for...in statement. AllImages is a asociative array with no numeric indexes. for (var image in AllImages), image will be 'left', then 'center', then 'right' (the names of the properties of the object you're using). So a statement like
AllImages[image+1]
will return 'undefined' and your code will throw an error. Your code should look like this:
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage"; center:"centerimage"; right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{
document.getElementById(allImages[image]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
By the way, I suggest you to read some documentation about loops in javascript, like MDN

how to concatenate text with image in a variable

Hello first i am basic to java script i have a some on mouse over divs which every one
contains information along images. the problem is that i want to combine text with an image
inside a variable whenever i am mouse hovering each divs so the information along the image
should change as i did program for every one of them
the problem is that how to combine the text and image inside a variable
but i don't know how to do that here is the code:
<script type="text/javascript">
function ENGshowElements(){
var Engineering = "Your In Engineering Section <br> <img src='a.jpg'>";
document.getElementById("contents").innerHTML = Engineering;
}
function CONshowElements(){
var Construction = "Your In Construction Section";
document.getElementById("contents").innerHTML = Construction;
}
function LLCshowElements(){
var LLCDubia = "Your In LLC Dubia Section";
document.getElementById("contents").innerHTML = LLCDubia;
}
function WASshowElements(){
var WasteManagement = "Your In Waste Management Section";
document.getElementById("contents").innerHTML = WasteManagement;
}
function TRAshowElements(){
var Transportation = "Your In Transportation Section";
document.getElementById("contents").innerHTML = Transportation;
}
function LOGshowElements(){
var Logistics = "Your In Logistics Section";
document.getElementById("contents").innerHTML = Logistics;
}
</script>
<div class="firstbox" id="Engineering" onmouseover="ENGshowElements(); return false; " >Engineering</div>
<div class="secbox" id="Construction" onmouseover="CONshowElements(); return false; ">Construction</div>
<div class="thirdbox" id="LLCDubia" onmouseover="LLCshowElements(); return false; " >LLC Dubia</div>
<div class="fourthbox" id="WasteManagement" onmouseover="WASshowElements(); return false; " >Waste Management</div>
<div class="fivthbox" id="Transportation" onmouseover="TRAshowElements(); return false; " >Transportations</div>
<div class="sixthbox" id="Logistics" onmouseover="LOGshowElements(); return false; " >Logistics</div>
DEMO: jsFiddle
HTML:
<div class="firstbox" id="Engineering">Engineering</div>
<div class="secbox" id="Construction">Construction</div>
<div class="thirdbox" id="LLCDubia">LLC Dubia</div>
<div class="fourthbox" id="WasteManagement">Waste Management</div>
<div class="fivthbox" id="Transportation">Transportations</div>
<div class="sixthbox" id="Logistics">Logistics</div>
<div id="contents"></div>
JS:
document.getElementById('Engineering').onmouseover = ENGshowElements;
document.getElementById('Construction').onmouseover = CONshowElements;
document.getElementById('LLCDubia').onmouseover = LLCshowElements;
document.getElementById('WasteManagement').onmouseover = WASshowElements;
document.getElementById('Transportation').onmouseover = TRAshowElements;
document.getElementById('Logistics').onmouseover = LOGshowElements;
function ENGshowElements() {
var Engineering = "Your In Engineering Section <br> <img src='a.jpg'>";
document.getElementById("contents").innerHTML = Engineering;
}
function CONshowElements() {
var Construction = "Your In Construction Section";
document.getElementById("contents").innerHTML = Construction;
}
function LLCshowElements() {
var LLCDubia = "Your In LLC Dubia Section";
document.getElementById("contents").innerHTML = LLCDubia;
}
function WASshowElements() {
var WasteManagement = "Your In Waste Management Section";
document.getElementById("contents").innerHTML = WasteManagement;
}
function TRAshowElements() {
var Transportation = "Your In Transportation Section";
document.getElementById("contents").innerHTML = Transportation;
}
function LOGshowElements() {
var Logistics = "Your In Logistics Section";
document.getElementById("contents").innerHTML = Logistics;
}
=> jsfiddle http://jsfiddle.net/Gy5rH/
just for the sake of making things clear, and pointing out that you're probably going the wrong way, here is a better alternative. It could probably be done mostly using css but here's something more easier to maintain.
Instead of using multiple triggers, We will use only one click function on every button. Each button will have a "data-target" which is the id of an other element.
Our markup will look like this:
<html>
<head>
<style>
#source { display: none; }
</style>
<script>
// Our click event
function clickEvent (ev) {
// Get the target in the dom
// While checking more about event should be good because
// Target may not be the element you're looking for in some cases.
var target = ev.target.dataset['target'];
var obj = document.getElementById(target);
// change the content with the one found
document.getElementById('content').innerHTML = obj.innerHTML;
}
function loaded() {
var docs = document.getElementsByClassName("btn");
// Transform to array
docs = Array.prototype.slice.call(docs);
docs.forEach(function(elem) {
// Assign click event to all elements
elem.onclick = clickEvent;
});
}
</script>
</head>
<body onload="loaded()">
<div>
<button class="btn" data-target="Engineering-Source">Engineering</button>
...
</div>
<div id="content"></div>
<div id="source">
<div id="Engineering-Source">
Your In Engineering Section <br> <img src='a.jpg'>
</div>
...more after
</div>
</body>
</html>
I added comments, but it's a nice way to do. Avoiding "vanillajs" might not be a bad thing but. It can be done without much pain in vanillajs.
That said, here are some reasons why it's good. The content remains in the html instead of javascript. If a web spider will download your page, there are far more chances that it will look for html content instead of text in javascript source.
In my example, some things might not exists in old browser like "dataset" and "forEach".
Note
That said, a pure "css" way of doing this is possible but might make the structure of the document harder to edit. On the other hand, there are ways to mix css and js to keep a minimum of js and as much as possible html/css to keep the styles in line.
Anyway, my example above should be working in some browsers to give an idea how to do it. I recommend using libraries like jQuery or prototype if you're not familiar with Javascript yet. The code above shouldn't definitely end up in production.

Categories