Here is what I was attempting with my code:
Here is my JavaScript:
var lastOne;
function selection(event) {
event.target.style.width = "50px";
lastOne.style.width = "10px";
current = event.target.id;
lastOne = document.getElementById(current);
}
Here is the relevant HTML:
<img src="images/Star.png" id="pic1" onclick="selection(event)">
<img src="images/Star.png" id="pic2" onclick="selection(event)">
Currently, it is editing the width of the element clicked, but does nothing to the previous element.
The first time selection
is called, lastOne
hasn't been assigned anything and the JavaScript throws an error and will stop working from this point on as lastOne
will never get assigned to anything.
var lastOne;
function selection(event) {
event.target.style.width = "50px";
//an error will get thrown on this line the first time the function is executed because lastOne has not been defined
lastOne.style.width = "10px";
current = event.target.id;
lastOne = document.getElementById(current);
}
I would fix it by doing this:
var lastOne;
function selection(event) {
if(lastOne) {
lastOne.style.width = "10px";
}
event.target.style.width = "50px";
current = event.target.id;
lastOne = document.getElementById(current);
}
Everything works fine except the one thing: if the lastOne
variable doesn't has a value, the error will be occurred, so you have to check, does this variable has any value. In you case if (lastOne) {//do stuff}
will be enough:
var lastOne;
function selection(event) {
event.target.style.width = "150px";
if (lastOne) {
lastOne.style.width = "50px";
}
current = event.target.id;
lastOne = document.getElementById(current);
}
img {
width: 100px;
max-width: 150px;
height: auto;
}
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/29/Gold_Star.svg/2000px-Gold_Star.svg.png" id="pic1" onclick="selection(event)">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/29/Gold_Star.svg/2000px-Gold_Star.svg.png" id="pic2" onclick="selection(event)">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With