Editing Javascript Variables

Here is what I tried with my code:

  • Click an item that has a selection () function.
  • The function sets the width of the element.
  • The function selects the pre-click element (which also has a select function ())
  • The function changes the width of the previous element

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)"> 

He is currently editing the click width of an element, but does nothing for the previous element.

+5
source share
2 answers

When you lastOne selection lastOne first time, nothing is assigned, and JavaScript throws an error and stops working from this point, since lastOne will never be attached 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 this by doing the following:

 var lastOne; function selection(event) { if(lastOne) { lastOne.style.width = "10px"; } event.target.style.width = "50px"; current = event.target.id; lastOne = document.getElementById(current); } 
+5
source

Everything works fine, except for one thing: if the lastOne variable lastOne not matter, an error will occur, so you need to check if this variable has any value. In your case, if (lastOne) {//do stuff} would 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)"> 
+1
source

Source: https://habr.com/ru/post/1274600/


All Articles