Add click event to dynamically added button to kendo window content - javascript

I have kendo window and im adding content dynamically to kendo window.
The content has a button and i wanted to attach click event to that button.
jQuery is able to find the button from the content, attach click event however click event never gets fired
JSFiddle
Html
<div id="example">
<div id="window">
</div>
</div>
JQuery
$(document).ready(function() {
// in reality this contnet will be returned from ajax call
var dynamicContent ="<div><button id='btn' type='button'>Click Me</button></div>"
var myWindow = $("#window")
var button = $(dynamicContent).find("#btn");
// show number of buttons found.
alert("found " + button.length + " button")
// attach click event to button
button.click(function(){
alert("this is test");
})
myWindow.kendoWindow({
width: "600px",
height:"200px",
title: "My Window"
}).data("kendoWindow").center().open().content(dynamicContent);
});

You need to change:
button.click(function(){
alert("this is test");
})
to
$('#window').on('click', 'button', function(){
alert("this is test");
})
As you mentioned the element is dynamically created, so it is not part of the browsers dom structure, and therefore can't be selected with jQuery. Using the above code, jQuery listens for any changes to the dom structure inside the #window element, so you can then select any dynamically created elements.

Related

jQuery does not recognize PHP generated child element when clicked

I am working on a website on which I have to display buttons based on database content. Clicking these buttons should then send a request to the database and reload the content of the page appropriately.
Everything is done with Ajax and jQuery by executing PHP scripts.
I can generate the buttons, but jQuery does not trigger when they are clicked.
It seems that jQuery detects a click on the div containing the buttons but not on the buttons themselves.
I was told that it may be because the jQuery script is loaded before the page is updated with the new HTML content.
This is the div container for all the choice buttons:
<div id = "choices">
<!-- Choices button will be displayed here -->
</div>
Here's the PHP code creating the HTML for the buttons:
echo " <button class = 'choice' id = \"$id\">
$content
</button> ";
This code is loaded in the previous #choices div by this jQuery code :
$.post("php_script/getChoices.php",
function(result){
$("#choices").html(result);
});
Pretty basic, and the expected (and actual) output on the webpage is :
<div id = "choices">
<button class = 'choice' id = "1">
Yes.
</button>
<button class = 'choice' id = "2">
No.
</button>
</div>
But when I write this :
$(".choice").click(function());
It never triggers, no matter how basic the function.
However, having another event to interact with the buttons is possible.
For example, the code below does hide the buttons when the #choices div is clicked.
$("#choices").click(function(){
$(".choice").hide();
});
In order to understand the problem, I wrote this jQuery script that print the content of the element that was clicked on the console.
$("*").on('click', function(event){
event.stopPropagation();
console.log('Clicked: ' + $(this).html());
});
And when I click on a button, it always returns the whole #choices div instead of just the content of the button.
As I said, I think this is because I am trying to interact with HTML elements that were added after the jQuery script was loaded (it is written in the section of my page).
Is my assumption correct and what should I do in order to trigger an action when the button themselves are clicked ?
You can always target the document to trigger dynamically created elements:
$(document).on('click', '.choice', function (e) {
e.preventDefault(); //stop default behaviour
var id = this.id; //get element ID
$(this).hide(); //hide element
});
As mentioned you can use event delegation
$(function(){
$("#choices").on("click", "button", function(){
alert("clicked");
});
});
Or manually bind the event handler when you add the new buttons
// called each time new buttons are added
function bindOnClick(){
$("#choices").off();
$("#choices").on("click", "button", function(){
alert("clicked");
});
}
$(function(){
// called once when dom is ready
bindOnClick();
});
If you don't call off you will bind the onclick event to the same element more than once.

Detect click event in any nested element of an specific div

I need to be able to detect any click that happens within a specific container referenced by class, if the user clicks on any of the nested elements I should be able to detect the click and update a flag
<div class="container" >
<div class="x1">
<div class="x2">
<div class="">
<span class="">
<ul class="">
</div>
</div>
I tried using jquery but I prefer to do it using backbone.
//$(document).on('click','.container', function(e){
//$('.container').delegate("div", "click", function(e) {
Not sure what event I need to use when the users are clicking in some of the nested elements within the div that have the container class. Basically, I need to update a flag in case of the user clicks outside of this div, but I don't want to have a large scope on the event handler that listens to the whole body.
Since you asked for a Backbone example, here's how to listen to clicks on a div and its children.
var View = Backbone.View.extend({
className: "my-test-view",
template: '<div class="container"><div class="x1"><div class="x2">test</div></div></div>',
events: {
'click .container': 'onClick',
},
render: function() {
this.$el.empty().append(this.template);
return this;
},
onClick: function(e) {
console.log("clicked on", e.target, " triggered from ", e.currentTarget);
},
});
var view = new View();
$("body").append(view.render().el);
Clicking the test text should output:
clicked on <div class=​"x2">​test​</div>​ triggered from <div class=​"container">​…​</div>​
With jQuery, the above is (roughly) the equivalent to:
$('.my-test-view').on('click', '.container', function(e) {
console.log("clicked on", e.target, " triggered from ", e.currentTarget);
});
But for most case, this should be enough:
$('.container').on('click', function(e) {
console.log("clicked on", e.target, " triggered from ", e.currentTarget);
});
Don't use .children().on(...) as this will create a new listener for each child and it's inefficient.
Detecting a click outside a div is quite different and there are many ways to achieve it but none is perfect.
See :
Backbone view with custom event to detect clicks outside of it
How to detect a click outside an element?
Use jQuery to hide a DIV when the user clicks outside of it
Personally, I used focus and blur events (don't forget tabindex="-1" on the element).
Maybe this?:
$(document).on('click','.container *', function(e){
console.log(e.target);
});
The great thing about jQuery is that you can use the same selectors as you would use with CSS hence I used .container * to target all elements inside the container.
I used the jquery .children() method. Check out this code pen.
var flag = 'whatever';
$(.container).children().on('click', function() {
flag = 'updated';
});
Essentially, saying for all children of whatever element is class container (div in this case) add an event handler.

jQuery dialog is not working for element created dynamically

I am working with jQuery dialog. I have one problem that trying to solve that is:
I have created the dialog on click of of anchor class and its working. Than after this I have created one more anchor tag with same class and on click of that new created tag dialog is not working.
Here is html:
<div id="loader_ajax"></div>
<a id="show_hide_window1" class="show_hide_window" href=""> Dialog </a>
<div class="next_tg"></div>
Here is jQuery code:
$(function(){
$(".show_hide_window").click(function(){
showDialog();
});
$('.next_tg').html('<a class="show_hide_window" href=""> Dialog Created By Jquery </a>');
});
function showDialog()
{
$("#loader_ajax").dialog({ modal: true, height: 400,width:650,title: title });
return false;
}
I have already tried with delegation(Event binding) its not working. For Dynamically created anchor it give error in console: TypeError: $(...).dialog is not a function
Please help!! Thanks
You can currently binding click event to elements that are present in the DOM when binding code executes. You need event delegation for dynamically created elements. You also need to add the newly create element to DOM, suppose you want to add to loader_ajax
Here static parent could be any html element, in your case it would be loader_ajax
You code would be
$("#loader_ajax").on("click",".show_hide_window", function(){
showDialog();
});
var newTextBoxDiv = $(document.createElement('div'));
newTextBoxDiv.html('<a class="show_hide_window" href=""> Dialog Created By Jquery </a>');
$("#loader_ajax").append(newTextBoxDiv);
Delegated events
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers.
Use on Event. This will manage dynamically added elements.
$(function(){
$('body').on('click', '.show_hide_window', function() {
showDialog();
})
$('.next_tg').html('<a class="show_hide_window" href=""> Dialog Created By Jquery </a>');
});
Fiddle : http://jsfiddle.net/fqt0yztb/
Reference : In jQuery, how to attach events to dynamic html elements?
I have make it from my own code. Now dialog successfully working for dynamically created element.
fiddle
$(document).on('click', '.show_hide_window', function (evt) {
var dialog = $('<div></div>').append('<img src="../images/themeroller.gif"/>');
var getContentUrl = $(this).attr('href');
dialog.load(getContentUrl + ' #content').dialog({
title: $(this).attr('title'),
modal: true,
height: 400,
width:650
});
dialog.dialog('open');
return false;
});

How to get the inside div element child and handle event in extjs4

I want to select the div with class "icon-right" and add the click event.
Html code:
<div class="msg">
<div>
<div class="sample"></div>
</div>
<div>
<div class="icon-right"></div>
</div>
</div>
I want to select the div which has class icon-right and handle click event..
Extjs code:
var message = Ext.select('div:next(div.icon-right)');
message.on('click', function () {
alert('test msg');
}, message);
But i need to change the div with class icon-right as div with icon-left when on click and now when i click the icon-left it change to div with class icon-right.. vice versa happens
Can you do:
Ext.select('.icon-right').up('div').on('click', function() {});
As per the documentation, Ext.select returns a CompositeElement or a collection of DOM elements. You should be using Ext.query which will return an HTMLElement, which you can then define the onclick event handler:
var target = Ext.query(".icon-right").pop(); // return the first div of the query
target.onclick = function(){ alert('clicked!'); }
Alternatively, if you wish to utilize Ext event listeners, you must make use of the Ext.dom.Element class, an instance of which is returned by Ext.get, which calls for an ID, DOM Node or Existing Element as per the documentation. If you were to retrieve the element via Ext.get, you could then assign a listener via Ext.dom.Element.on as you have in the provided code.
Working jsFiddle: http://jsfiddle.net/LcRWB/ (shows both examples)
This should work.
var el = Ext.Element.select("[class=icon-right]");
el.on('click', function() {
alert("hi");
});
You can see an example on jsfiddle http://jsfiddle.net/XzKKZ/

Jquery appending with styling and functions

i appending buttons with some IDs and i use those IDs to make on click stuff
when it appending didn't take button() effect
and on click it don't take the function that I created it for this button id
$("button#edit-doc").each(function() {
$(this).button();
$(this).on("click", function(){
alert("clicked");
});
});
append button
$("#append").on("click", function(){
$('div#container').append("<button id='edit-doc'> Edit </button>");
});
container
<div id="container"></div>
This seems to be what you're after:
function handler() { alert('clicked'); }
$("#append").on("click", appendButton);
function appendButton(){
$('#container').append(function() {
return $("<button id='edit-doc'> Edit </button>").on("click", handler);
})
}
http://jsfiddle.net/PF8xY/
See jQuery how to bind onclick event to dynamically added HTML element for more information on this behavior.
$(document).on("click", "#selector", function(){
//Your code here.
});
Using document for your selector with .on will allow you to bind events to dynamically created elements. This is the only way I've found to do it when the DOM elements don't exist prior to execution.
I do this in a dynamically created table that is sort-able and works great.
EDIT:
Here is an example. Click the button to add a div then click the div to get it's contents.
http://jsfiddle.net/FEzcC/1/
The first code-block attaches an event listner to all buttons with class='edit-doc', use classes instead of an id since an id's name may only exist once per page. So I was saying, when your browser reaches this code an event listner is added to all available buttons in your document at that moment. It doesn't add an event listner to buttons you will be adding later onclick of some element, because it doesn't know. You will have to explicitly execute the code again for the buttons that you append. But what you don't want is to add a new event listner to the original buttons, causing two events being called.
Something like:
// Load all buttons with class=edit-doc and add event listner
$(function() {
$("button.edit-doc").button().on("click", function(){
alert("clicked");
});
});
// Append button if button with id=append is clicked
$("#append").on("click", function(){
var button = $.parseHTML("<button class='edit-doc'>Edit</button>");
$('div#container').append(button);
$(button).button().on("click", function(){
alert("clicked");
});
});
Working example:
http://jsfiddle.net/RC9Vg/

Categories

Resources