Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript issue managing variables

Here is what I was attempting with my code:

  1. Click an element that has the selection() function.
  2. Function sets that element's width.
  3. Function selects previously click item (that also has selection() function)
  4. Function changes previous element's width

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.

like image 858
Robinhoodjj4 Avatar asked Jan 09 '18 16:01

Robinhoodjj4


2 Answers

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);
}
like image 64
Adam Avatar answered Sep 27 '22 19:09

Adam


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)">
like image 44
Commercial Suicide Avatar answered Sep 27 '22 21:09

Commercial Suicide