The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Adding Event Handlers

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #158958

    Hi guys,

    I’m in the process of learning to do certain things in javascript that I would use jquery for. One of the things I find tricky is adding event listeners to elements. I attached a codepen link to show what I have come up with this far. In the example I have a moving div that fires on a click event. It works, however, it works on a click anywhere on the DOM. It also will only fire twice then will stop. How can I attach this event to the button so the div will move? Thanks a lot for any help or insights as to how to make this possible. I apologize if this was a bit confusing or was written in an unclear manner.


    You can either attach the event listener directly to the element like:

    document.getElementById('click').addEventListener('click', slideOut, false); 

    Or use event delegation and check for target like:

    function slideOut(e) {
      if ( == 'click') {
        var outClass = document.getElementById('test'); // make sure you target the right element here
        outClass.className = outClass.className + 'move';

    It does not stop firing. First time it sets class to move, second time to movemove and so on. That’s why it looks like a toggle, but it isn’t. You can use classList to toggle, but it’s IE10+.

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.