Javascript simple onclick image swap - javascript

I am trying to use Javascript to swap an image, so far I can get it from A to B, but not back.
Here is what I'm using to create one swap:
<img src="pic1.png" name="pic" onclick="window.document.pic.src='pic2.png';"/>
This swaps image 1 to image 2, simple enough. But I want to be able to revert back to image 1 by clicking on the new image 2. I tried using this:
<img src="pic1.png" name="pic" onclick="
if (window.document.pic.src='pic1.png'){
window.document.pic.src='pic2.png';
}
else if (window.document.pic.src='pic2.png'){
window.document.pic.src='pic1.png';
}"/>
It doesn't seem to work in this instance. It will switch to pic2, but not switch back to pic1. Is it something to do with onclick? My if statements? Thanks

Try this simple trick... easy to maintain.
<script>
var onImg= "on.jpg";
var offImg= "off.jpg";
</script>
<img src="on.jpg" onclick="this.src = this.src == offImg ? onImg : offImg;"/>

In your code the problem is
when you alert window.document.pic.src its print like http://localhost/pic1.png
and then you are are use condition if (window.document.pic.src == 'pic1.png')
how is it true.
try this
<script type="text/javascript">
function test()
{
alert(window.document.pic.src);
//alert msg print like http://localhost/test/pic1.png
if (document.pic.src=='http://localhost/test/pic1.png'){
document.pic.src='pic2.png';
}
else if (document.pic.src=='http://localhost/test/pic2.png'){
document.pic.src='pic1.png';
}
}
</script>
<img src="pic1.png" name="pic" onclick="test()"/>

wrong use of == in if condition
if (window.document.pic.src == 'pic1.png'){
window.document.pic.src='pic2.png';
}
else if (window.document.pic.src =='pic2.png'){
window.document.pic.src='pic1.png';
}"/>

window.document.pic.src='pic1.png' assigns pic1.png to the left hand side. It does NOT compare.
Though not directly relevant, try not to access elements by their name globally. Use their id.
Your javascript should not be inside the onclick. It should be inside a javasctipt function
Combined:
The img tag:
<img src="pic1.png" name="pic" id="pic" onclick="swap()"/>
The javascript
<script>
function swap()
{
if (document.getElementById("pic").src.endsWith('pic1.png') != -1) //==:Comparison
{
document.getElementById("pic").src = "pic2.png"; //=:assignment
}
else if (window.document.pic.src.endsWith('pic2.png') != -1)
{
document.getElementById("pic").src = "pic1.png";
}
}
</script>

Your code is doing what the below lines do, it's not going inside an if else block, so if you remove your if else block the code still will work, because on mouse click it sets the value of src as 'pic2.png', which was 'pic1.png' earlier, and when you click again because it's already pic2.png so it remains the same.
<html>
<head>
<script type="text/javascript">
function swap() {
window.document.pic.src='pic2.png';
}
</script>
</head>
<body>
<img src="pic1.png" name="pic" onclick="swap()">
</body>
</html>

You can try this.
<html>
<head>
<title>Swapping Images</title>
</head>
<body>
<img id="myimg" src="img1.jpg" hieght="300" width="300" onClick="change ()"/>
</body>
</html>
<html>
<head>
<script>
function change () {
var img=document.getElementById("myimg");
if (img.src === "img1")
img.src="img2.jpg";
else
img.src="img1.jpg";
}
</script>
</head>
</html>

Related

Light Bulb in Javascript doesn't Turn On

<!DOCTYPE html>
<html>
<head>
<title>switch</title>
<script language="javascript" type="text/javascript">
function click_turn() {
if (document.getElementById("light").src == "/pic_bulboff.gif") {
document.getElementById("light").src = "/pic_bulbon.gif";
}
else {
document.getElementById("light").src = "/pic_bulboff.gif";
}
}
</script>
</head>
<body>
<img id="light" src="/pic_bulboff.gif" />
<br />
<button id="click" onclick="click_turn()">Click</button>
</body>
</html>
The button doesn't work, that is the light bulbs doesn't turn on. I searched in Google and didn't find any solution. What did I do wrong?
The HTMLMediaElement.src property reflects the value of the HTML media element's src attribute, which indicates the URL of a media resource to use in the element.
Instead of using src property, you should be using getAttribute to read the attribute of the Element which would not be URL but a value assigned.
function click_turn() {
if (document.getElementById("light").getAttribute('src') == "pic_bulboff.gif") {
document.getElementById("light").setAttribute('src', "pic_bulbon.gif")
} else {
document.getElementById("light").setAttribute('src', "pic_bulboff.gif")
}
}
<base href="https://www.w3schools.com/js/">
<img id="light" src="pic_bulboff.gif" />
<br />
<button id="click" onclick="click_turn()">Click</button>
using img.src will return an absolute path not a relative path so the document.getElementById("light").src will never equal to /pic_bulboff.gif. You can also add the baseurl to your logic or use .includes("") instead:
function click_turn() {
if (document.getElementById("light").src.includes("pic_bulboff.gif") {
document.getElementById("light").src = "/pic_bulbon.gif";
}
else {
document.getElementById("light").src = "/pic_bulboff.gif";
}
}
document.getElementById("light").src returns the full path ('http://etc').
try document.getElementById("light").src.endsWith("/pic_bulboff.gif")
Well, I replaced "==" by "endsWith" and it worked. Thank you for all the help.

On image click set input value jquery

Hi im trying to set an image from an input box and if i click another image the box change his value and then the first image change his src but i dont know why is not working.This is my script
$(document).ready(function() {
$("#skin").change(function() {
var inputVal = $(this).val();
$("#container").attr("src", inputVal);
});
});
$(document).ready(function() {
$("#container2").click(function() {
var source = document.getElementById("container2").src;
$("#skin").val(source)
});
});
<input type="text" id="skin">
<img id="container" width="200px" height="200px" border-radius="50%">
<img id="container2" src="http://i.imgur.com/xt0IkTL.png">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
First of all, you are using jQuery.
So you don't have to use native javascript dom selector.
Second; you have already defined your document ready function. You don't need to call that again.
Wrap your code between the first document ready function.
I strongly recommend you to change your on change method to something else like pressing a button or trigger with something else.
After all these recommendation;
Here how you can do this:
<input id="source-changer" type="text" placeholder="Image url huh?" />
<img id="container" width="200px" height="200px" border-radius="50%"><img id="container2" src="https://i.ytimg.com/vi/PjDtgj7qR94/maxresdefault.jpg" width="100">
<!-- sample address here: https://pp.vk.me/c622424/v622424967/39c6c/6poIwEXow7U.jpg -->
<script>
$(document).ready(function() {
var firstImage = $('#container');
var secondImage = $('#container2');
$('input#source-changer').blur(function(){
var value = $(this).val();
if(value !== "") {
firstImage.attr('src', value);
}
});
secondImage.click(function(){
firstImage.attr('src', $(this).attr('src'));
});
});
</script>
Test here:
https://jsfiddle.net/upLdgb8y/1/

How do I cycle through images with a single button?

I have just started coding javascript in notepad++ at a GCSE level.
One of my tasks in my Assessment is to make traffic lights change colour, one image for each button click.
I have got as far as Making the Red light change to a Red-Yellow light. However, I am unable to go further with this.
My code so far:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function lewis() {
document.getElementById("pic").src="Red-Yellow.png"
}
</script>
</head>
<body>
<button type="button" onclick="lewis()">
Change Lights</button>
<img src="Red.png" alt="Red" id="pic" style="width:250px;height:600px;">
</body>
</html>
This is the height of my ability as I have just started.
Any help would be appreciated, many thanks,
Lewis
(I will continue to do research alongside this question)
Didn't tested but i guess you want something like that.
function lewis() {
var current_image = document.getElementById("pic").src;
if(current_image == "Red.png"){
document.getElementById("pic").src = "Red-Yellow.png";
}else if(current_image == "Red-Yellow.png"){
document.getElementById("pic").src = "Red-Green.png";
}else if(current_image == "Red-Green.png"){
document.getElementById("pic").src = "last-color.png";
}else if(current_image == "last-color.png"){
document.getElementById("pic").src = "Red.png";
}
}

Variable not sent to other function

I have a number of links, that when clicked on, passes a variable thru to another portion of the page.
Yet, for some reason, I can’t figure it out! What am I missing?
<head>
<script type="text/javascript">
function myFunction(a){
myid="Hi There!"+a;
return myid;
}
</script>
</head>
<body>
Click Me<br />
<script type="text/javascript">
document.write(myid);
</script>
</body>
You are getting a little mixed up here. Even though the function returns a value, it has nothing to return it to. Try this:
<head>
<script type="text/javascript">
function myFunction(a){
myid="Hi There!"+a;
document.getElementById("debug").innerHTML = myid;
}
</script>
</head>
<body>
Click Me<br />
<div id="debug"></div>
</body>
if you want to use it later you need to declare myid as a global variable. its scope is currently only within myFunction. also the document.write() function will only execute at runtime so you need to have another function the executes that with every click, or just combine the two.
When you click the link all that happens is that the myFunction() is called which returns the string. The line document.write(myid); is not executed anymore so nothing is visible.
<script>
// This is global
var myid = ''
myfunc = function(a){
myid = "Hi There!" + a;
alert(myid);
}
test_global = function(){
alert(myid);
}
</script>
Set MYID
<input type="button" onclick="test_global();" value="Test MYID" />
Here is a simple example of some similar stuff:
clickme or ClickMeAlso
<input id='other' type='text'/>
<script>
function myfunc(a) {
return a + " howdy";
};
</script>
You can see this in action here:http://jsfiddle.net/5Sbn2/

W3Schools tutorial example not working with Coda on Mac

I am following a JavaScript tutorial on the W3Schools website and I have the following code:
<html>
<head>
<title>Hello!</title>
</head>
<body>
<script type="text/javascript">
function confirmShow
{
var r = confirm("Press one...")
if (r == true)
{
alert("Button pressed == OK")
}
if (r == false)
{
alert("Button pressed == Cancel")
}
}
</script>
<input type="button" onclick="confirmShow()" value="Show Confirm Box" />
</body>
</html>
and whenever I preview it in Coda or in Safari the alert never shows up.
Thanks in advance!
"function confirmShow" => "function confirmShow()"
Firebug is good for js debugging, try it. Safari has options too, AFAIK.
function confirmShow
{
function confirmShow()
{
?
I don't know if this is your problem, but your button is outside the <body> tag. That might cause you some trouble...
Also one would usually put a script like this in the <head> element. Just FYI.
1) w3schools is filled with errors and omissions. Better tutorials can be found at howtocreate.co.uk
2) You have no DOCTYPE declaration, and you're using XHTML syntax.
2.1) IE doesn't support true, see webdevout.net/articles/beware-of-xhtml for more information
3) You need to encapsulate the within a element as well as another block-level element as per the specification
See below for a proper HTML5 document. Notice the location and syntax
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
<script>
function confirmBox() {
var ret = confirm('Some Text');
/*
Note the 3 equal signs. This is a strict comparison operator, to check both the 'value' as well as the type. see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators for more
*/
if(ret === true) {
alert('Alert box for "Okay" value');
}
else if(ret === false) {
alert('Alert box for "Cancel" value');
}
}
window.onload = function() {
// Execute the confirmBox function once the 'button' is pressed.
document.getElementById('confirmBox').onclick = confirmBox;
}
</script>
</head>
<body>
<form>
<p>
<input type="button" id='confirmBox' value="Show Confirm Box">
</p>
</form>
</body>
</html>

Categories

Resources