0

Hi there Stackers,

I'm back with another problem. It's Javascript (again). I've been creating "alerts" for on my webpage. They contain a button, and I want to close them when I click on a button. However, this doesn't seem to work. I've logged the clicks in the console, and the click is logged. The click does happen.

The Alerts hide after a few seconds. When I change the style with the "Devtools" of Chrome to make it visible again, and click the button then, the DIV does dissapear.

Why does the click not hide my div?

Javascript

var messageId = 0;

    var alerty = function(type, title, content) {
        messageId++;
    var html = ' <div class="alert" id="a-' + messageId + '"><div class="topview ' + type + '"></div><div class="title">' + title +'</div> <div class="text">' + content +'</div> <input type="button" id="close-'+ messageId + '" class="inputbutton-empty ' + type + '2 button close" value="Meldung schlie&szlig;en"></div>'
    $(html).hide().appendTo("#alertcontainer").fadeIn("fast");
    $(".alert").delay(8000).fadeOut();
    $("#close-" + messageId ).click(function() {
        console.log("XTM: Pushed Alerty alert closed on request.");
        $("#a-" + messageId ).hide("fade", "fast");
    });
}

Thanks in advance, Pascal

Pascal Boschma
  • 187
  • 1
  • 14
  • Log `$("#a-" + messageId )` and see if you get what you expect. – Malk Jun 01 '16 at 22:29
  • @Malk Yes, I get the at that opened div logged in the console, however, it does not hide. – Pascal Boschma Jun 01 '16 at 22:32
  • So the event is triggering and you are targeting the correct element...what's left? Add a `debugger` line after the log and use the javascript console to work out the jquery syntax that works. – Malk Jun 01 '16 at 22:36

2 Answers2

0

It is probably the delay() that is preventing your hide() call. Try clearing the queue first in your close function:

$("#close-" + messageId ).click(function() {
        console.log("XTM: Pushed Alerty alert closed on request.");
        $("#a-" + messageId ).stop().hide("fade", "fast");
    });
Malk
  • 11,855
  • 4
  • 33
  • 32
0

It's probably because you need to use .on instead of .click.

.on is for newly created DOM elements, which you are doing with your html.

See: jQuery function not binding to newly added dom elements and http://api.jquery.com/on/

Community
  • 1
  • 1
Phillip Chan
  • 993
  • 7
  • 17