0

I am using Jquery to display notification at the top of my webpage. I am using the following function to display the notification bar -

function myBar(message) {
    $("<div />", { class: 'mybar', text: message, id: 'mymsg' }).hide().prependTo("body")
      .slideDown('slow');
}

And in $(document).ready(function(){ I am calling the myBar("my message");, with appropriate css. It is displaying the bar as required.

Now I want to hide the bar when one clicks on the bar. For that I am trying this

$("#mymsg").click(function() {
     $(this).remove();
})

But this is not working as such. Any suggestions on what might be wrong?

PRYM
  • 513
  • 4
  • 12
  • 1
    See this [jQuery $(this).remove() not working after append](http://stackoverflow.com/questions/9665646/jquery-this-remove-not-working-after-append) –  Feb 07 '13 at 13:49

2 Answers2

3

If your div doesn't yet exist when you add the event handler, the jQuery set $("#mymsg") is empty and no event handler is added.

You could use on instead :

$(document.body).on('click', "#mymsg", function() {
     $(this).remove();
});

Or, if you prefer, you could bind the event when you add the div :

function myBar(message) {
    $("<div />", { class: 'mybar', text: message, id: 'mymsg' }).click(function(){
       $(this).remove();
    }).hide().prependTo("body").slideDown('slow');
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • I was thinking of same kind of problem but was not sure how to tackle that. Its working fine now. thanks – PRYM Feb 07 '13 at 13:49
1

When the page loads the message element doesn't exist yet in the DOM, so the click event handler is not bound to the element.

Since this seems to be a one-time message, consider chaining the event handler directly in the creating function. For example:

function myBar(message) {
    $("<div />", {
        class: 'mybar',
        text: message,
        id: 'mymsg'
    }).hide().prependTo("body").slideDown('slow').click(function() {
        $(this).remove();
    });
}
Boaz
  • 19,892
  • 8
  • 62
  • 70