Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

addEventListener

I want my div to expand when you click on it to 500px using pure javaScript only. I am working on my js skill. What am I doing wrong here?

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
     <link rel="stylesheet" href="css/styles.css" media="screen" title="no title" charset="utf-8">
    <title> Css | JavaScript</title>
  </head>
  <body>
      <section>
          <div id="mydiv">

          </div>
      </section>

      <script src="js/main.js"></script>
  </body>
</html>
#mydiv {
    width:300px;
    height:300px;
    background:tomato;
    color:#fff;
    border-radius:50%;
    margin:100px auto;
    box-shadow:1px 2px 5px;
}
function changeSize() {
   var getId = document.getElementById('mydiv');
    getId = this;
    this.style.width = '500px';
    this.style.height = '500px';
    this.style.background = "crimson";
    getId.addEventListner("click",changeSize, false)
}

changeSize();

2 Answers

You are adding the event listener within the changeSize function. What you need to do is call changeSize as the eventHandler function. You add the event listeners outside the function, then the target of the event is passed into the callback function, so you can automatically use 'this' to reference it. It also means that your changeSize function can be called on any element, so your code becomes more flexible and reuseable.

Should read something like this:

function changeSize() {
    this.style.width = '500px';
    this.style.height = '500px';
    this.style.background = "crimson";
}

 var getId = document.getElementById('mydiv');
getId.addEventListner("click", changeSize);

'''
Hope this helps

Thank you . I understand it now.