How to change image on click [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
So I want to change an image onClick and change it back oClick.
This is my current code, but for some reason it doesn't work. I can't find out what's wrong with it.
var newsrc = "suspects.png";
var newsrc = "questionmark.png";
function changeImage() {
if ( newsrc == "suspects.png" ) {
document.images["img"].src = "/images/suspects.png";
document.images["img"].alt = "suspects";
newsrc = "questionmark.png";
}; else {
document.images["img"].src = "/images/questionmark.png";
document.images["img"].alt = "questionmark";
newsrc = "suspects.png";
};
};
I´m pretty sure it´s good like this... Why doesn´t it work?

Toggle a image only checking the source
function toggle(){
var img=document.getElementById('img');
img.src=img.src=='url1'?'url2':'url1';// needs to be the full url.
}
Regarding you code:
you define newsrc 2 times and so the first one is lost.newsrc is always "questionmark.png"
}; else{
should be
}else{
and
if you have suspects set then you want questionmark if clicked, and not suspects.so invert the if content.
should be
if suspects then questionmark else suspects
you have
if suspects then suspect else questionmark.
DEMO
http://jsfiddle.net/SLkHu/

Remove extra semicolons ; in your code
It should be
function changeImage() {
if ( newsrc == "suspects.png" ) {
document.images["img"].src = "/images/suspects.png";
document.images["img"].alt = "suspects";
newsrc = "questionmark.png";
} else {
document.images["img"].src = "/images/questionmark.png";
document.images["img"].alt = "questionmark";
newsrc = "suspects.png";
}
}

Related

If statements JavaScript, maths will not work in my else statement what am I doing wrong? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This question is pretty straightforward. I am making a number guessing game and I am now adding an attempts function to my game. Every failed attempt should add 1 to my attempts variable:
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
console.log(numberwang);
console.log(attempts);
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
console.log("Attempts:",attempts)
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
console.log("Attempts:",attempts)
}
}
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
However the else statement argument doesn't work. Each attempt does not add anything to my attempts variable. Can anyone see what is wrong? Thanks in advance.
Note: the else statement is not working for anything mathematical.
You are defining a variable everytime you click.
Removing the "var" from inside the if/else block
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
<script type="text/javascript">
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
console.log(numberwang);
console.log(attempts);
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
}
}
</script>
Your problem is that when you use the var keyword, you are making a new variable. You should remove the var inside both the if and the else. This will let you change the outer attempts variable, and not the new one that you define by using the var.
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
}
console.log("Attempts is: "+attempts);
}
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
I think that I understand what you are having a problem with. You expect what is already logged to the console to change when the variable changes. That's not how console.log works. It only logs the current value of the variable. If you want to see the new value, you should log it again, in this case after each guess is made.

Javascript doesn't work in Internet Explorer but in all other browsers. Why? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
The below Javascript (triggering the pagination background color of an element, when another element scrolls into view) doesn't work in Internet Explorer but in all other browsers. Does anyone have any idea why?
The code basis is also available in my pen: https://codepen.io/headstarterz/pen/PMdZdV/
<script>
function inViewport(element) {
// Get the elements position relative to the viewport
var bb = element.getBoundingClientRect();
// Check if the element is outside the viewport
// Then invert the returned value because you want to know the opposite
return !(bb.top > innerHeight || bb.bottom < 0);
}
var project1 = document.querySelector(".project-trigger1");
var project2 = document.querySelector(".project-trigger2");
var project3 = document.querySelector(".project-trigger3");
var pagination1 = document.querySelector(".bullet1");
var pagination2 = document.querySelector(".bullet2");
var pagination3 = document.querySelector(".bullet3");
// Listen for the scroll event
document.addEventListener("scroll", event => {
// Check the viewport status
if (inViewport(project1)) {
pagination1.style.background = "#e3e3e3";
} else {
pagination1.style.background = "transparent";
}
});
document.addEventListener("scroll", event => {
// Check the viewport status
if (inViewport(project2)) {
pagination2.style.background = "#e3e3e3";
} else {
pagination2.style.background = "transparent";
}
});
document.addEventListener("scroll", event => {
// Check the viewport status
if (inViewport(project3)) {
pagination3.style.background = "#e3e3e3";
} else {
pagination3.style.background = "transparent";
}
});
</script>
Script works in Chrome, Safari, Firefox, Edge
Script doesn't work in Internet Explorer 11
It is probably two reasons:
Firstly your closing <script> tag is spelled wrong (<skript>).
Also, you're using 'fat arrow functions', which is a feature of ES6. I would look into something like Babel to transpile your code to a I.E. friendly syntax

How to "echo" a variable from a Javascript function into html? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm using the function below to rotate images on click into the #home-image div, beginning with the first image.
Javascript:
$('#home-image').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'img1_on.jpg') src = 'img2_on.jpg';
if (origsrc == 'img2_on.jpg') src = 'img3_on.jpg';
if (origsrc == 'img3_on.jpg') src = 'img4_on.jpg';
if (origsrc == 'img4_on.jpg') src = 'img1_on.jpg';
$(this).attr('src', src);
}
});
HTML:
<img id="home-image" src="img1_on.jpg" />
But
I want to "echo" the file name of the image being displayed, so the viewer sees the name of the image.
How would I "echo" the name of the image into another div, i.e. <div id="home-image-name"></div>?
This is an attempt to echo the output of src into the home-image-name div, but it doesn't work:
$('#home-image').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'img1_on.jpg') src = 'img2_on.jpg';
if (origsrc == 'img2_on.jpg') src = 'img3_on.jpg';
if (origsrc == 'img3_on.jpg') src = 'img4_on.jpg';
if (origsrc == 'img4_on.jpg') src = 'img1_on.jpg';
$(this).attr('src', src);
var output = 'src';
document.getElementById("#home-image-name").innerHTML = output;
}
});
This works, with the additional window.onload functions to show the image name on page load:
window.onload = function(){
$("#home-image-name").html($('#home-image').attr("src"))
$('#home-image').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'img1_on.jpg') src = 'img2_on.jpg';
if (origsrc == 'img2_on.jpg') src = 'img3_on.jpg';
if (origsrc == 'img3_on.jpg') src = 'img4_on.jpg';
if (origsrc == 'img4_on.jpg') src = 'img1_on.jpg';
$(this).attr('src', src);
var output = 'src';
document.getElementById("home-image-name").innerHTML = src;
}
});
}
So, from what I said + #j08691 comment, the correct sintax would be:
document.getElementById("home-image-name").innerHTML = src;
As the getElementById method takes a string of the id, with no need of #. And output was just a string, so you could either change output = src which is kind of redundant, or just put src.
Jquery way:
$("#home-image-name").html(src)
If you want to also do it on page load before click:
window.onload = function(){
$("#home-image-name").html($('#home-image').attr("src"))
}
Using jQuery, a simple:
$('#home-image').click(function(){
$('#home-image-name').html(this.src.split('/').pop())
})
should work.
jsFiddle example
Also if you wanted to use this code with several images, you could use the following (which uses a common class):
$('.home-image').click(function(){
$('#home-image-name').html(this.src.split('/').pop())
})
jsFiddle example
remove the # from
document.getElementById("#home-image-name").innerHTML = output;

why is this if statement not doing anything? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Believe me the HTML won't be necessary on this one since the if statement only deals with the cBox variable. What this does is, create or close a div upon clicking a button, i've tested the functions and they work, what's not working however is the way these functions are called, I've logged the outputs but i get neither of them displayed in the console, this means the code is not running through the if statement for some reason.
Also tried with if (cBox == null) and it doesn't work ...
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('cBox');
console.log(" but cbox is "+cBox);
if(cBox) {
closecBox();
console.log("cbox exists, closing ...");
} else {
opencBox();
console.log("cbox does not exist, creating...");
}
};
I am not sure i understand your question but if your code is like this seems to work fiddle
function closeBox(elem){
elem.parentNode.removeChild(elem);
}
function openBox(el){
var el = document.createElement('div');
el.setAttribute("id", "cBox");
document.body.appendChild(el);
}
var btnPress = document.getElementById('button');
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('cBox');
if(cBox) {
closeBox(cBox)
console.log("cbox exists, closing ...");
} else {
openBox(cBox);
console.log("cbox does not exist, creating...");
}
};
If i did not understand your question sorry for having done wasting time.
Guys thank you for all the replies, your hints were definitely helpful for solving this problem, i made so many changes that i lost track but this is the working code
var btnPress = document.getElementById('theBtn');
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('confirmBox');
console.log("cbox is "+cBox);
if(cBox) {
console.log("cbox exists, closing ...");
closecBox();
} else {
opencBox();
console.log("cbox does not exist, creating...");
}
};
function opencBox() {
var cBox = document.createElement('div');
cBox.id = "confirmBox";
document.body.appendChild(cBox);
cBox.style.display="inline";
};
function closecBox() {
var cBox = document.getElementById('confirmBox');
cBox.style.display="none";
document.body.removeChild(cBox);
};
I also used display style to test some other stuff with animations :) once again, thank you so much for all the comments! They really helped me out figuring the solution!

If a checkbox is checked or unchecked - code optimization - jquery [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
So I have a jquery "checkbox checked/unchecked" function working well. This is a checkbox for turning on or off a particular URL parameter - BUT I believe this code could be written a lot tighter. Does anyone have any suggestions?
$('#mapControl').live('click', function(){
var thisUrl = $(location).attr('href');
if($(this).is(':checked')) {
var lastFour = thisUrl.substr(thisUrl.length - 4);
var param;
if (lastFour == 'com/') {param='?mapControl=true'} else {param='&mapControl=true'}
thisUrl=thisUrl+param;
} else {
$('#urlParam').val(thisUrl);
if (thisUrl.indexOf('?mapControl=true') >= 0){
thisUrl=thisUrl.replace('?mapControl=true','');
} else if (thisUrl.indexOf('&mapControl=true') >= 0){
thisUrl=thisUrl.replace('&mapControl=true','');
}
}
$('#urlParam').val(thisUrl);
});
Try to avoid jQuery as much as you can for example
$('#mapControl').live('click', function(){
// you can directly read window location href attribute
var thisUrl = window.location.href;
var urlParamObj = $('#urlParam');
// instead of $(this).is(':checked') YOU can write *this.checked === true*
if(this.checked === true) {
var lastFour = thisUrl.substr(thisUrl.length - 4);
var param;
if (lastFour == 'com/') {param='?mapControl=true'} else {param='&mapControl=true'}
thisUrl=thisUrl+param;
} else {
urlParamObj.val(thisUrl);
/* if you are sure that your location may have "?mapControl=true" OR "&mapControl=true"you don't have to write code to check string directly replace
*/
thisUrl=thisUrl.replace('?mapControl=true','');
thisUrl=thisUrl.replace('&mapControl=true','');
}
// you don't have to write $('#urlParam') 2 times create a object and refer it again and again
urlParamObj.val(thisUrl);
});

Categories