1

I am learning javascript and I have a problem with changeimage function.

I need to change both one, and second image.

Here is jsfiddle.

https://jsfiddle.net/7ewjoxnv/1/

And here below, javascript:

var switchingImage; function changeImage() { switchingImage.src = this.value; } window.onload = function() { var radios = document.getElementById('imageSwitcher').getElementsByTagName('input'); switchingImage = document.getElementById('imageToSwitch'); for(var i=0;i<radios.length;i++) { radios[i].onclick = changeImage; } var radios = document.getElementById('imageSwitcher2').getElementsByTagName('input'); switchingImage = document.getElementById('imageToSwitch2'); for(var o=0;o<radios.length;o++) { radios[o].onclick = changeImage; } } 

Any help will be much appreciated.

Best Regards, David!

1 Answer 1

1

When you do var radio = and switchingImage = for the second time, you are changing their previous values.

In the case of radios it just happens and does not affect you because you have already applied the listeners you wanted to the old radio buttons.

In the case of switchingImage however, it affects you, because switchingImage will ultimately point to the document.getElementById('imageToSwitch2'). So when you call changeImage() it will always operate on document.getElementById('imageToSwitch2').

Here's one way you could solve your problem. It is purposefully not the best solution. Use it as a baseline to improve on it.

https://jsfiddle.net/7ewjoxnv/4/

Sign up to request clarification or add additional context in comments.

1 Comment

Thank You Mitch for Your professional approach! It works perfectly and I will upgrade it from this point easly!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.