jQuery dialog is not working for element created dynamically - javascript

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;
});

Related

javascript click event not firing action

On page load, I have a search box that, once used, populates a div with multiple images. The javascript from the search uses this function to append all images into the div
function appendSomeItems(url, id, name, style) {
return '<div><div class="md-card md-card-hover"> <div id="getImage" class="gallery_grid_item md-card-content"> <img class ="uk-align-center imageClick"></a> <div class="gallery_grid_image_caption"> <span class="gallery_image_title uk-text-truncate">' + name + '</span> <span>' + style + '</span> </div></div></div></div>';
}
This works perfectly. Now I'm trying to make it so that when I click any one of the images it triggers an action (in this case a console log)
$('.imageClick').click(function handleImage() {
console.log(good);
});
However, it does nothing. No error but no console log.
What am I doing wrong here?
You need to use event-delegation in order to bind an event to dynamically created elements:
This approach uses document as the parent element, however, a good practice is to use the closest parent element.
$(document).on('click', '.imageClick', function handleImage() {
console.log(good);
});
Try with .on() to attach event on dynamically created element. This will allow attaching the event to the elements that are added to the body at a later time:
$('body').on('click', '.imageClick' function handleImage() {
console.log(good);
});
The problem is that you are calling $(".imageClick").click() before you dynamically create the items.
This means that jQuery doesn't actually bind the click listener to the items, since when $(".imageClick").click() is run, the elements don't actually exist yet.
Try this:
$("body").on("click", ".imageClick", function handleImage() {
console.log("good");
});
Also see this post for more information: In jQuery, how to attach events to dynamic html elements?

Magnific PopUp not Working with the Dynamically Added Elements

We are using the Magnific library to display the PopUps in our site. Everything with this is going well except one thing.
when we add an element dynamically, popup is not working for the dynamically added elements. Can you please help me how I can bind the click event for the dynamically added element to display the popup? Here is my code is given below:
`<a id="del-vis-archive-new-{{$request->id}}" href="#delete-visitor-archive" data-id="{{$request->id}}" class="popup-form-delete-visitor-archive" style="color:red;"><i style="color:red; text-align: right;" class="hi hi-trash"></i></a>
var PopupDelVisArchive = function() {
$('.popup-form-delete-visitor-archive').magnificPopup({
type: 'inline',
preloader: false,
focus: '#name',
callbacks: {
open: function() {
var dataId = $(this.st.el).attr('data-id');
$("#btn").attr('data-id', dataId);
}
}
});
}
$(document).on( 'init.dt, draw.dt', function ( e, settings ) {
PopupDelVisArchiv();
});`
The class is responsible for displaying the pop-up
but it doesn't work for the dynamically added elements.
In other words, the click event is not getting registered in the DOM for the newly added elements.
You need to bind the popup to each new element after they are loaded in the dom. That means calling PopupDelVisArchiv(); for each new element once dom ready.

Adding event listener on a replaced HTML DOM

I am using the tooltipster jquery plugin to show title in a nicer way. In my site there is a link with two classes .fav tooltip
<div class="actsave">
Save
</div>
The .tooltip is use to take the above anchor title and display it according to the tooltipster plugin.
$('.tooltip').tooltipster();
This works just fine, but when a user will click on this link the entire DOM will be replace with a new DOM.
$("div.actsave").on("click", "a.fav", function(e){
e.preventDefault();
$(this).replaceWith('Delete');
});
At this point no events are occurring with the new anchor with .del class.
My question is how i can add a event listener to this newly created dom in jquery?
After doing some research i fix it this way:
$("div.actsave").on("mouseover mouseout", "a.del", function(e){
$(e.target).tooltipster();
});
but it seems that we are adding same event again and again without any reason to the dom when we hover the link, so here is the question can we add an event listener to this newly created dom just for once?
$("div.actsave").on("click", "a.fav", function(e){
e.preventDefault();
var newElement = $('Delete');
$(this).replaceWith(newElement);
newElement.tooltipster();
});
Create a flag to keep track using data()
$("div.actsave").on("mouseover mouseout", "a.del", function (e) {
if (!$(this).data('triggered')) {
$(e.target).tooltipster();
$(e.target).data('triggered', true);
}
});

How to disable links even after adding a new link?

I would like to disable clicking on links in the preview and show an error message instead. I came up with a simple solution:
<div id="preview">
<p>There is a sample link that should not follow to google.com</p>
<ul></ul>
</div>
<button id="btn">Add a new link</button>
JavaScript code:
$('a').on('click', function () {
alert("links are disabled");
return false;
});
$('#btn').on('click', function () {
$('#preview ul').append('<li><p>another link</p></li>');
});
It works perfectly fine for the already existing links but not for the new links added via the button.
How to disable links even after adding a new link?
I would like to keep the logic for disabling links out of the code for adding a new links (as there are multiple places that are adding a new link)
JS fidddle: http://jsfiddle.net/bseQQ/
To capture events on dynamic elements you need to use a delegated selector:
$('#preview').on('click', 'a', function () {
alert("links are disabled");
return false;
});
This is because events are attached on load, and obviously dynamic elements do not exist at that point. A delegate event is attached to a parent element, but only fired when the filtered selector bubbles the event through the DOM.
Working demo http://jsfiddle.net/P6Hbg/
API: .on - http://api.jquery.com/on/
This should fit your cause :)
code
$(document).on('click','a', function () {
alert("links are disabled");
return false;
});
You'd better use event delegation:
$('#preview').on('click', 'a', function() {
alert('links are disabled');
return false;
});
Here #preview is used as a static parent element.
$('#btn').click(function () {
$('#preview ul').append('<li><p>another link</p></li>');
});

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