views:

49

answers:

2

I'm trying to make a notification area that will show alerts.

return this.each(function() {
  jQuery('<div class="' + o['className'] + '">' + o.msg + ' +
         '<a href="#" onclick="$(this).parent().remove(); dismiss(' + o["id"] + ');">X</a>' + '</div>')
    .appendTo(this);
});

This just takes a message pulled from the database, and shows it to the user. If the user clicks the X then it will call dismiss() which will mark it as being read in the database.

The thing is, if the message itself contains a link to another page or external site, I also want to call dismiss() before the user leaves the page. Is there anyway to alter this javascript to take all a elements (the X and any links that would appear in the message) and change the onclick to call the function?

+1  A: 

The code example is a bit vague, where does this o come from? Is it global or something div-specific?

At any way, you may find jQuery.live() useful for this. Once initialized, it will be applied on all future new elements matching the selector. You only need to have some parent element which is going to contain all of those divs with the messages and the links.

$('#someDivId a').live('click', function() {
    // Do your thing here as you did in `onclick` attribute.
};

Just execute it once during onload.

BalusC
+1  A: 

You can rearrange your code a bit and use .delegate(), like this:

return this.each(function() {
  var id = o["id"];
  jQuery('<div />', { 'class': o['className'], html: o.msg })
   .append('<a href="#">X</a>')
   .delegate('a','click', function() { $(this).parent().remove(); dismiss(id); })
   .appendTo(this);
});

This uses the new jQuery(html,props) added in jQuery 1.4 to make the creation a bit cleaner (and faster! document fragment caching!). What it's doing is instead of attaching an onclick to the X, it's listening for a click from any <a> in the div and when it bubbles, it executes the same code as it used to only on the <a href="#">X</a> anchor.

Nick Craver
@Brandon - Sounds like you have a funky character in there, are you talking about the `X` portion or the `o.msg` portion? Worst case, you can remove `, text: o.msg` and add a `.html(o.msg)` in the chain.
Nick Craver
The o.msg portion. I actually gave the X link a class to separate it from the message links (so I could float it to the right) and now the o.msg portion works. I'm not really sure why. However I don't believe this worked. It generated the link without the click.
Brandon
@Brandon - You won't see the `onclick` in the html, it's an event handler, put an `alert(id)` in the delegate's function to see it getting clicked.
Nick Craver
Oh, I also had to change `text: o.msg` to `html:`. It also doesn't like the `class:` syntax.
Brandon
Okay, I feel stupid. Works great >_> Thanks!
Brandon
@Brandon - Woops, anything not a jQuery call (e.g. `'class'`) needs quotes, updated :)
Nick Craver