SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    click event seems to fire twice

    Hello,

    I am trying to understand better events:

    Code JavaScript:
     
    (function(){
     
     
    var self = TestEvent = {
     
    	element: '',
     
    	doSomething: function(e){
                    self.element = this;
    		e.stopPropagation()
    		alert(self.element);
    		return false;	
    	},
     
    }
     
    var myElements = getElementsByClassName('test-elements');
     
    for (var k in myElements) {
     
    	myElements[k].addEventListener("click", TestEvent.doSomething , false);	
    }
     
     
    })();

    When a link is clicked that triggers the "click" event, the element is alerted BUT the browser follows the link, as if the "return false" was not working.

    1. What could cause this? What am I missing?

    2. I feel like my code is poorly designed. Could someone be kind enough to tell how to refactor such a simple snippet (so I dont find myself caught once the code gets more complicated).


  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,600
    Mentioned
    24 Post(s)
    Tagged
    1 Thread(s)
    return false doesn't prevent the default when you are using event listeners (it only works with event handlers).

    For event listeners you prevent the default action using"

    e.preventDefault();
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •