Help with addEventListener

Help with addEventListener
0

#1

Hi everyone! I am just learning JS, and I got stuck in simple addEventListener codes. Can anyone help me understand why the “click” isn’t working in the code below? Thank you!

Teste
		function cor(){
		var cx = document.getElementById("dv1");
		cx.style.border="2px solid green";
		cx.style.width="200px";
		cx.style.height="200px";
		cx.style.borderRadius="50%";
		cx.style.backgroundColor="blue"; 
		}
		
		function changeColor(){
		var obj=getElementById("dv1");
		obj.style.background-color("red");
		}
		
		function doTheChange(){
		document.addEventListener("click", changeColor);
		}
		
		window.addEventListener("load",cor);
		window.addEventListener("load",doTheChange);
		
		</script>
</head>
	<body>
	<div id="dv1"></div>

		
</body>

#2

You have a couple of issues.

#1) You are missing something before the getElementById.

var obj=getElementById("dv1");

#2) Not really sure what you are trying to do with the following:

obj.style.background - color("red");

There is no color function in your code and even if there was, why are you subtracting color(“red”) from obj.style.background? Did you mean to put = instead - ?

What exactly do you want to happen if someone clicks on the document? I assume you are trying to make the background color of the circle red? If so, you can look at your existing code in the cors function you created, where you set the background color to blue.


#4

Thank you, I managed to turn the circle red when clicked after you pointed out the errors!! Here’s the new code:

Teste
		function cor(){
		var cx = document.getElementById("dv1");
		cx.style.border="2px solid green";
		cx.style.width="200px";
		cx.style.height="200px";
		cx.style.borderRadius="50%";
		cx.style.backgroundColor="blue"; 
		}
		
		function changeColor(){
		var obj=document.	getElementById("dv1");
		obj.style.backgroundColor="red";
		}
		
		function doTheChange(){
		document.addEventListener("click", changeColor);
		}
		
		window.addEventListener("load",cor);
		window.addEventListener("load",doTheChange);
		
		</script>
</head>
	<body>
	<div id="dv1"></div>

		
</body>

#5

Might I suggest the following refactors of your code to make it easier to read and reduce unnecessary lines of code.

#1)

<!DOCTYPE html>
<html>
<head></head>
<body>
  <div id="dv1"></div>
  <script>
  function cor() {    
    function changeColor() {
      circle.style.background = "red";
    }
    
    var circle = document.getElementById("dv1");
    circle.style.border = "2px solid green";
    circle.style.width = "200px";
    circle.style.height = "200px";
    circle.style.borderRadius = "50%";
    circle.style.backgroundColor = "blue";
    document.addEventListener("click", changeColor);
  }

  window.addEventListener("load", cor);
</script>
</body>
</html>

#2) Using CSS classes

<!DOCTYPE html>
<html>
<head>
  <style>
    .circle {
      border: 2px solid green;
      width: 200px;
      height: 200px;
      border-radius: 50%;
      background-color: blue;
    }

    .red {
      background-color: red;
    }
  </style>
</head>
<body>
  <div id="dv1" class="circle"></div>
  <script>
    function cor() {
      function changeColor() {
        var circle = document.getElementById("dv1");
        circle.classList.add('red');
      } 
      document.addEventListener("click", changeColor);
    }
    window.addEventListener("load", cor);
  </script>
</body>
</html>

#6

Thank you very much! Now if possible I’d like to review another code where I’m trying to move the circle:

!DOCTYPE html>
<html lang="pt-br">
	<head>
		<title> Teste </title>
		
		<meta charset="utf-8"/>
		<script>
			
		function editCircle(){
		var cx = document.getElementById("dv1");
			cx.style.border="2px solid green";
			cx.style.width="200px";
			cx.style.height="200px";
			cx.style.borderRadius="50%";
			cx.style.backgroundColor="blue"; 	
		}	
		
			var dx;
			var dy;
			var px;
			var py;
			var spe;
			var obj;
			var tmp;
						
			function initiate(){
				dx=0;
				dy=0;
				px=0;
				py=0;
				spe=10;
				obj=document.getElementById("dv1");
				document.addEventListener("keydown",teclaDw);
				document.addEventListener("keyup", teclaUp);
				setInterval(enterFrame,20);
				}
			
			function teclaDw(){
				var tecla=event.keyCode;
				if(tecla=37){
					dx = -1;
				}
				else if(tecla=38){
					dy = -1;
				}
				else if(tecla=39){
					dx = 1;
				}
				else if(tecla=40){
					dy = 1;
				}
			}
			
			function teclaUp(){
				var tecla=event.keyCode;
				if(tecla==37){
					dx=0;
				}
				else if(tecla==38){
					dy=0;
				}
				else if(tecla==39){
					dx=0;
				}
				else if(tecla==40){
					dy=0;
				}
			}
			
			function enterFrame(){
				px+=dx*spe;
				py+=dy*spe;
				obj.style.left=px+"px";
				obj.style.top=py+"px";
			}
			
			window.addEventListener("load", editCircle);	
			window.addEventListener("load", initiate);	
															
			
			</script>
			
			
	</head>
	<body>
		<div id="dv1"></div>
			
			
	</body>
</html>

#7

Explain what you expect to happen with the code you have written.


#8

I expect to move the circle with my keyboard.


#9

But how are you expecting to move the circle with the keyboard?


#10

I hoped the keyboard arrows on the function teclaDw() atributed the value of 1 and -1 to dx and dy, so that those variables when multiplied by ‘spe’ on the function enterFrame() changed the element dv1 position on the screen. The function teclaUp() is to stop the movement when the keyboard arrows are no longer pressed.


#11

You are using style.top and style.left, but those only work if the element has a position property set to absolute or relative.

Also, in your teclaDw function, make sure you are using equal operator instead of the assignment operator to compare the various key codes.

In general your up, down, left, and right logic for the teclaDw function does not do much. Currently, when you press one of the arrow keys, you are assigning either -1 or 1 to dx and/or dy. This means no matter what arrow key you press, the circle will always never move out of the upper left-hand corner. You need to increment or decrement dx and dy instead of assigning it just a value of -1 or 1.

EDIT: I corrected your code to achieve what you were going after and also simplified the code to a single function for keyup or keydown events (see moveCircle function).

function initiate() {
  function drawircle() {
    var cx = document.getElementById("dv1");
    cx.style.position = "relative";
    cx.style.border = "2px solid green";
    cx.style.width = "200px";
    cx.style.height = "200px";
    cx.style.borderRadius = "50%";
    cx.style.backgroundColor = "blue";
  }
  
  function moveCircle ({type, keyCode}) {
    var keys = {
      37: {x: -1, y: 0},
      38: {x: 0, y: -1},
      39: {x: 1, y: 0},
      40: {x: 0, y: 1}
    };
    
    if (type === "keydown") {
      var {x, y} = keys[keyCode];
      dx += x;
      dy += y;
    }
    else if (type === "keyup") {
      dx = dy = 0;
    }
  }

  function enterFrame() {
    px += dx * spe;
    py += dy * spe;
    obj.style.left = px + "px";
    obj.style.top = py + "px";
  }
  
  var dx = 0, dy = 0;
  var px = 0,  py = 0;
  var spe = 10;
  var obj = document.getElementById("dv1");
  drawircle();
  document.addEventListener("keydown", moveCircle);
  document.addEventListener("keyup", moveCircle);
  setInterval(enterFrame, 0);
}
window.addEventListener("load", initiate);

#12

Hmmm I see! Thanks again for the help, it worked!
If it’s not too much to ask, could you explain me the moveCircle() function you made? You assigned the x,y values to an array with the keys in a function that calls an event? I think I haven’t got to this part of my studies yet!

Thank you very much!


#13

keys is an object which has keyCodes as property names which contain objects with properties x and y. The values of the x and y properties are referenced from the keys object and assigned to x and y variables using what known as destructuring (the {x, y} = keys[keyCode] part). If you are using the FCC curriculum, there is a whole section about destructuring.