Javascript for changing image source not working - javascript

I am making a simple website which changes the image displayed when a button is clicked. But my code doesn't seem to be working as when I click on the button 'Click!' the alt text gets displayed instead of the image changing.The source of the images is perfectly fine, as when I use the same source outside the script the images show up.
<head>
<title>Pic Change</title>
<meta charset="utf-8">
<meta name="Pic Change">
<meta name="keywords" content="face,PES">
<meta name="author" content="Thalle">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
</head>
<body class="body" style="background-color:#4682B4">
<script>
function display(whichimage){
if(whichimage == 0){
document.getElementById('Click').src="C:\.....\Memes\Animals\initial.jpeg"
}
else{
document.getElementById('Click').src="C:\.....\Memes\Animals\Whenlife.jpeg"
}
}
</script>
<image id="Click" src="C:\......\Memes\Animals\initial.jpg" alt="Click Button to click picture" style="width:300px;height:300px" >
<p>
<button type="button" onclick="display(1)">Click!</button>
<button type="button" onclick="display(0)">Reset</button>
</p>
</body>
</html>

The code is fine, you just forgot the file:// before the start. This code shows that when you give a working image src in your code, it will work just fine. Also, don't use files from your disk on Stack Overflow, it gives out private information that you probably don't want on the web.
<head>
<title>Pic Change</title>
<meta charset="utf-8">
<meta name="Pic Change">
<meta name="keywords" content="face,PES">
<meta name="author" content="Thalle">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
</head>
<body class="body" style="background-color:#4682B4">
<script>
function display(whichimage){
if(whichimage == 0){
document.getElementById('Click').src="http://www.iconarchive.com/download/i86425/martin-berube/flat-animal/duck.ico"
}
else{
document.getElementById('Click').src="https://maxcdn.icons8.com/Share/icon/Animals//duck1600.png"
}
}
</script>
<image id="Click" src="http://www.iconarchive.com/download/i86425/martin-berube/flat-animal/duck.ico" alt="Click Button to click picture" style="width:300px;height:300px" >
<p>
<button type="button" onclick="display(1)">Click!</button>
<button type="button" onclick="display(0)">Reset</button>
</p>
</body>
</html>

You forgot the protocol (file://). It should be like
document.getElementById('Click').src="file://C:\Users...";
otherwise it will be just appended to the src everytime you click a button.

Try to put your JavaScript in the <head> section. Then it might work.
Also. There is no such thing as image in HTML. It's img.

In javascript, you need to escape backslashes in strings, so in adresses in particular. Replace all "\" by "\\".

You shouldn't load images from your disk. We and others can't see it. If you use relative paths and you make sure every images and the HTML file is in the same directory, that should be fine. Even if you do, you must specify the file:// protocol. But if you use external images from a website, we could see them.
There is no <image> element in HTML. It's just <img>.
You should type \\ instead of \, because the \ character has a special meaning. However, Javascript is smart, and you can use / too, don't have to follow Windows' method.
Please don't use the onclick attribute. It's really old. Instead use event listeners.
Right now I don't know what is the problem in your code extacly, however, there is a working example:
<!DOCTYPE html>
<html>
<title>Pic Change</title>
<script>
document.addEventListener("DOMContentLoaded", function() {
document.querySelector("button").addEventListener("click", function() {
document.querySelector("img").setAttribute("src", "file://C:/Data/300x300-colored.png");
});
});
</script>
<p><img src="file://C:/Data/300x300.png" /></p>
<p><button type="button">Click!</button></p>
</html>
If both images and the index.html is in the C:\Data directory, it works fine.

Related

Changing elements in an HTML file using javascript onclick event

I've been learning HTML and CSS this semester and originally started to code my project in HTML and CSS, but in order for my project to work, I had to link HTML pages to each other. It ended up making a lot of HTML pages just to change one line of text. I've been trying to get a handle on JavaScript to make my project more efficient. My HTML code looks like this:
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Oakwood</title>
<meta name="viewport" content="width=device-width; initial-scale=1.0;">
<link rel=stylesheet type=text/css href=default.css>
</head>
<body>
<div id=back></div>
<div id=drdick></div>
<div id=choice></div>
<div class="typewriter">
<script src="run.js"></script>
<p id=text>While out running someone says “Hi” causing you to trip. He helps you up.</p>
</div>
<div id=move>
<button type="button" onclick="changeThis()">Next</button>
</div>
</body>
</html>
My Javascript Looks like this:
var quoteIndex = 0;
var quotes = [
"Thank you.",
"Are you ok?",
"Yes, I’m not normally this clumsy"
];
function changeQuote() {
++quoteIndex;
if (quoteIndex >= quotes.length) {
quoteIndex = 0;
}
document.getElementById("text").innerHTML = quotes[quoteIndex];
}
function showPic()
{document.getElementById("drdick").src="img/drdickab.png";}
function changeThis() {
changeQuote();
showPic();
}
when I test my code my quotes update how I want them to. My picture does not show up at all. Is there something I am missing when it comes to how HTML and Javascript interact? I have been looking through the forums to figure out what I have wrong, and I haven't been able to figure that out.
Your image is not displaying because you did not specify your image anywhere in your markup, and your javascript is also not enough. But try this inside your body tag:
<body>
<!--replace your button with this code.-->
<div id=move>
<button type="button" onclick="showMyImage();" value="Next"></button>
</div>
<!--I assumed you will display the image just below your button, note that initially your image is hidden and displayed on button click event-->
<div>
<img id="myImage" src="img/drdickab.png" style="visibility:hidden"/>
</div>
</body>
.
<!--There's really no need to have multiple scripts, just one will do the job-->
<script type="text/javascript">
function showMyImage(){
document.getElementById('myImage').style.visibility="visible";
}
</script>

Turning Grayscale off on IE11 when loading page

I have been trying to implement an accesibility function for a Website and one of my requirements is having a grayscale activated or deactivated on the click of 2 links. The users are still on Internet Explorer 11, so the compatibility with that navigator is a must.
So far, I have implemented some styles and code I found on the web and those are working great, I adapted the code, so I have 2 hyperlinks that execute a javascript function. One for enabling the grayscale and another one for disabling it.
But I have an issue, the grayscale is always turned on from the start whenever I load the page. I would like the grayscale starting disabled and then being enabled on by the click of one of my links.
Testing with Chrome and Firefox, the grayscales are turned off by default by adding the "grayscale-off" class to my images. Despite this, the issue persists on Internet Explorer.
So, I tried forcing the call to my javascript function that disables the grayscale on several parts:
Body
<body onload='enableEG(null)'>
Images themselves
<img src="img/FOV_8967.JPG" alt="Goal 1" width="600" height="400" class="grayscale grayscale-off" onload="enableEG(null)">
On the required script tag
<script src="js/jquery.gray.min.js" onload="enableEG(null)"></script>
Even tried creating a new script tag all the way to the bottom of my code, just before closing the body tag.
<script>enableEG(null);</script>
Interestingly, I put a couple of alerts that pop up when the function is executed, and they do appear when loading the page in IE with those forced function calls, however, the images still are grayscaled initially.
Here's my entire html code for reference (without the forced calls to the function):
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Gray</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/gray.min.css">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script>
function enableEG(t){
var activeT = t;
//Internet Explorer
var isIE = /*#cc_on!#*/false || !!document.documentMode;
if (isIE) {
if ( activeT == null ){
alert ("activateEG1: NULL; disable");
$('.grayscale').toggleClass('grayscale-off',true);
}
else {
alert ("activateEG1: 1; enable");
$('.grayscale').toggleClass('grayscale-off',false);
}
}
//Other navigators
else {
if ( activeT == null ){
document.documentElement.style.webkitFilter = 'grayscale(0%)';
}
else {
document.documentElement.style.webkitFilter = 'grayscale(100%)';
}
}
}
</script>
</head>
<body>
<p>Grayscale Test</p>
<p><a id="linkEnable" href="#" onclick="enableEG(1);">Enable</a></p>
<p><a id="linkDisable" href="#" onclick="enableEG(null);">Disable</a></p>
<div class="gallery">
<a target="_blank" href="img/FOV_8967.JPG">
<img src="img/FOV_8967.JPG" alt="Goal 1" width="600" height="400" class="grayscale grayscale-off">
</a>
<div class="desc">Goal 1</div>
<a target="_blank" href="img/FOV_9088.JPG">
<img src="img/FOV_9088.JPG" alt="Goal 2" width="600" height="400" class="grayscale grayscale-off">
</a>
<div class="desc">Goal 2</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="js/jquery.gray.min.js"></script>
</body>
</html>
Any help will be appreciated!
Update:
Found that I can turn off the grayscale if I put a script executing on a Window Load event after calling the external js, and it works like a charm on a single index page!
<script>
$(window).on('load', function() {
alert ("script function: turn off gray");
enableEG(null);
});
</script>
However, I'm still looking for a more permanent solution, because this fix doesn't work on internal pages that go beyond the index of the site I'm testing.

Links not working in an absolute container with a positive z-index

The problem can be seen on the website I am developing https://manu354.github.io/portfolio/
The links in the header cannot be clicked. After a quick search on SO I realized this was because my div was positioned absolute. I had positioned it absolute, so it didn't take up any space in my page layout. To fix this, multiple answers said to add a z-index : 10; to my div. This let me click the links (Pointer / hover functionality worked) and completely fixed the problems for my external links to Facebook, or Twitter. However my internal functional links e.g href="#welcome"were clickable, however they didn't move to the area they were meant to (works if the div is positioned relatively).
For example (the actual codes much longer, and uses revolution slider)
<div style="position:absolute; z-index:1;">
<a href="#welcome" target="_self" style="z-index: 10;>
</div>
Anybody know a fix for this?
Thanks
The problem may be that you didn't put the ending double quotes in the a(anchor) tag the below code can help:
<!doctype HTML>
<html>
<head>
<title>codedamn HTML Playground</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/style.css" />
</head>
<body>
<div style="position:absolute; z-index:1;">
Hello world
</div>
</body>
</html>
Well it doesnt work because your links to an id "welcome" but the div's id is "welcome_forcefullwidth".
Welcome ID
If you remove "_forcefullwidth" or add on your href "_forcefullwidth" it will work
Not to mention that the rest of the IDs are nowhere to be found
I see on your website a lot of inline style and the website is too complex as it should. The code is not that clean.

javascript click a button and create an image in a div

I've searched this problem of mine and found some solutions but there is something wrong I must be doing because it doesn't work.
I would like to, simply, just press a button and make an image appear in a certain div. Later, I'd like to add more buttons and each button will correspond to an image changing this image in the same div.
My code is this:
<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
</style>
</head>
<body>
<button id="button1">Button 1</button><button id="button2">Button 2</button></br>
<button id="button3">Button 3</button><button id="button4">Button 2</button></br>
<p> </p>
<div id="1"></div>
<div id="2"></div>
<script type="text/javascript">
document.getElementById("button1").onclick=function() {
document.getElementById("1").appendChild="<img id="image1" src="img/image1.png" />;
}
document.getElementById("button2").onclick=function() {
document.getElementById("1").appendChild="<img id="image2" src="img/image2.png" />;
}
document.getElementById("button3").onclick=function() {
document.getElementById("2").appendChild="<img id="image3" src="img/image3.png" />;
}
document.getElementById("button2").onclick=function() {
document.getElementById("2").appendChild="<img id="image4" src="img/image4.png" />;
}
</script>
</body>
</html>
but somehow I cannot make this work.
You're using double quotes inside a string encapsulated by double quotes:
"<img id="image1" src="img/image1.png" />;
This needs to be
"<img id=\"image1\" src=\"img/image1.png\" />";
Since JavaScript uses quotes (single or double) to set strings you need to escape quotes inside a string with \ to avoid breaking the string. In your original code JavaScript is parsing the string, finds the end of the string at id= and breaks because it expects a line terminator ; or a +.
Look at the highlighting in the first and second code block. It's all red in the second indicating a correct escaped string.
ALSO
appendChild only works with nodes/elements and not with strings. You need innerHTML, however that will overwrite the content of your div every time. If you don't want that you could use: insertAdjacentHTML()
Example:
document.getElementById("1").insertAdjacentHTML("beforeend", "<img id=\"image1\" src=\"img/image1.png\" />");
Try this:
Javascript:
document.getElementById(<img id>).src = "<link to img>";
HTML:
<img id='<img id>' src='<link to img>'>

Calling input type in a function

The aim is that when the page is loaded, an onload call to a function will be made and inside this function will be an input type which will access a devices camera.
How can i call an input type inside a JavaScript function?
<!DOCTYPE HTML>
<html>
<head>
<title>Take Picture</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script type="text/javascript">
function getPic()
{
<input type="file" id="takePic" style="display: none;" accept="image/*;capture=camera">
}
</script>
</head>
<body onload="getPic()">
EDIT : The line of code below allows access to the device's camera, which works fine.
<input type="file" id="takePic" accept="image/*;capture=camera">
basically what i want is, when the page loads, it automatically clicks the choose file button from the above piece of code. I assumed the best way to do this was by JS. I may be wrong.
I have very little knowledge of JS so i came here for help after finding little on the net.
If you want to add input in body use document.write
function getPic()
{
document.write('<input type="file" id="takePic" style="display: none;" accept="image/*;capture=camera">');
}
If you want to access that input use getElementById().
document.getElementById('takePic')
If your goal is taking a snapshot from a webcam, you might be better off using the navigator.getUserMedia() API.
See this page for details: http://www.html5rocks.com/en/tutorials/getusermedia/intro/
It's unsupported in IE and Safari, but works in current versions of Firefox, Chrome and Opera: http://caniuse.com/#feat=stream

Categories