[ 3 posts ]

spazlon

  • Joined: Mon Jul 26, 2010 5:11 am
  • Posts: 2
  • Offline
  • Profile

addListener(click) fires on load

Post Posted: Mon Jul 26, 2010 5:19 am
+0-
I have an element that i have assigned a click event listener to. When the page loads the event fires.

This is my element:

Code:
xInnerHtml(li,'<p class="cart" id="unique_id_from_js">blah blah blah</p>');

var tmp = xGetElementById('unique_id_from_js');
YAHOO.util.Event.addListener(tmp,'click',alert('blah'));


Every time the page loads it alerts "blah". I even used FireBug and ran the addListener command after the page had already loaded and it immediately alerts.

Am I missing something here?

If you need the entire JS file I will post it.

Thanks!

- Ryan

Dav Glass

  • Username: davglass
  • Joined: Thu Aug 28, 2008 9:28 am
  • Posts: 2088
  • Location: Marion, IL, US
  • Twitter: davglass
  • GitHub: davglass
  • Gists: davglass
  • IRC: davglass
  • Offline
  • Profile

Re: addListener(click) fires on load

Post Posted: Mon Jul 26, 2010 5:22 am
+1-
Ryan --

You are not attaching a listener, you are firing a method:

This is firing the alert, since it has ()'s around it:
Code:
YAHOO.util.Event.addListener(tmp,'click',alert('blah'));


This will work because it passes a function reference to the listener:

Code:
YAHOO.util.Event.addListener(tmp,'click', function() {
    alert('blah');
});


Hope that helps..

spazlon

  • Joined: Mon Jul 26, 2010 5:11 am
  • Posts: 2
  • Offline
  • Profile

Re: addListener(click) fires on load

Post Posted: Mon Jul 26, 2010 6:24 am
+0-
That's great!

You have no idea how long I was racking my brain trying to figure out what I was doing wrong!

I even had function () { alert('blah'); } for a while and it still didn't work. Pasted exactly what you had and it worked great!

Thanks!
  [ 3 posts ]
Display posts from previous:  Sort by  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum