Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select dynamically created html element

There are a lot of asked questions with almost similar titles with this question of mine, but you know I didn't find an answer.

My simple question is: I have button, when I click on it, javascript creates modal window

<div class="aui-dialog">
     html here... 
     <button id="closeButton">Close</button>
</div>

just after <body> tag.

I can bind click event of close button with no problem using jQuery live:

$("#closeButton").live("click", function() { 
    alert("asdf"); // it calls
    $("body").find(".aui-dialog").remove();
});

My problem is, I cannot select that dynamically created modal window div by its classname. So that I could call jQuery .remove() method to make close action. Now I know, I must deal with dynamic elements in another way.

What way?

EDIT:
I think it's important to mention this:
I dont' create the modal window myself, I use liferay portal. It has built-in javascript framework AUI(YUI) that creates that modal window. I can just create that close button inside it in its view.

EDIT 2:
Modal window div class attribute value is: "aui-component aui-panel aui-dialog aui-widget-positioned"

like image 750
Almas Adilbek Avatar asked Apr 23 '12 12:04

Almas Adilbek


People also ask

How to bind click event to dynamically created html elements in jQuery?

on() method. In the example, I have created an unordered list and a button for adding new list items. In the script, attach click event on #lists li selector to change the background color of clicked <li> . Append a new <li> to the <ul> element on the add button click and also attaching click event on <li> using .

How do you add an event to a dynamic button?

To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click .


1 Answers

Since jquery will read the current DOM-state when page loads:

jQuery( document ).ready(function( $ ) {

it will miss the elements you generate post to page load.

One simple solution is to listen for clicks on document, and filter with the class or element-type that you want to use to execute your code. That way jquery will find new elements generated under document, after page load.

$(document).on("click", '#closeButton', function(){
$(".aui-dialog").remove();
});
like image 103
JUlinder Avatar answered Sep 22 '22 03:09

JUlinder