I'm loading some html using jQuery function .load() and everything works fine. The problem is that I need to select some of the dynamic created elements to apply some styles with JS. For example:
$(".new-element-class").datepicker();
I know that dynamically added elements are not part of DOM and that I can trigger events this way:
$("body").on("click", ".new-element-class", function() {});
I have read a lot of answers with that solution but that's not what I need. I want to select and apply a function without having to wait for an event. I also tried find() and it didn't work.
You need to call .datepicker() in the code that adds the new element dynamically. You can do this in the callback function of .load()
$("#element").load("url", function() {
$(this).find(".new-element-class").datepicker();
});
Related
I have some code that creates an accordion with a select2 element which has a class called docType. I also have jquery code to trigger an event on selecting a value of the jquery element. While this works for select2 elements that already exist on the page load, it doesn't trigger for dynamically added elements. Here is my on change code:
$('.docType').on('change', function() {
// the code inside should be firing for dynamically added elements
}
Does anyone know why this way isn't working?
Use event delegation for dynamically added elements.
$(document).on("change",".docType", function() {
Us the 'on' method to delegate events. This will add a handler to dynamically generated elements.
$(document).on("change",".classnameyouarewatching", function() {
//Your code
}
on method definition
If your elements are being dynamically loaded, you'll need to use something more like what's below. For instance, say you're dynamically generating via AJAX or something similar the following input element:
<input type="text" class="text_element" value="some value">
To add event handlers to that element try using JS like this:
<script type="text/javascript">
$(document).on('change', '.text_element', function() {
console.log('Element with class "text_element" has changed');
console.log('New value is: ' + $(this).val());
});
</script>
The answer above is correct, but it is not just the 'on' handler that delegates the handling of dynamically generated DOM elements. The actual trick here is to place the handler on the document as it will always exist rather than the element or element class as you have above. It is the handler on document, looking for elements of a class (2nd param of the on event) that gets the job done you're looking for.
I think u need to call find() method for all the select element before firing on change method like below
$(".docType").find(":select").on( ("change", function() { // the code inside });
If it does not work, try JQuery instead of $.
I have been searching this on internet, I have found some answers which were helpful like but they were not enough to solve my problem (e.g.
Similar Problem but no solution provided for my problem)
I am using JRate plugin, I am adding a div inside a div using jQuery. The problem is that when I add it using jQuery and use the JRate Functions then they are not working. But they are working without appending a new div.
I know how to make it work. I will have to use $(document) but I dont know how to use it with this code.
Here is HTML
<div class="jRate"></div>
Here is my Jquery
$(".jRate").jRate({
onSet: function(rating) {
alert(rating);
}
});
Here is my appending code
var divjRate = "<div class='jRate'></div>";
$(divjRate).appendTo('.fb-jRate');
Can any one tell me how can I use $(document) here or any other alternative solution you have.
You need to append the html element first so that it is registered in the DOM. Then, you can call jRate on it
var divjRate = "<div><div class='jRate'></div></div>";
// Append new element to container of choice
$(divjRate).appendTo('.fb-jRate');
// Use plugin on new element
$('.jRate').jRate({
onSet: function(rating) {
alert(rating);
}
});
The solution you have linked applies to binding event listeners, which is not the case with a typical jQuery plugin that usually involves DOM replacement and other things.
You will need to apply the method to newly added DOM elements. The DOM mutation event specification is deprecated due to performance issues, and it is not realistic to expect the browser to keep track of all changes (and what kind of changes) happening in the DOM.
For example, if you're adding new content with an AJAX call, you can apply the method to newly added content within the jqXHR.done() function.
Update: OP provided with some code, so I have adding a way to initialize the plugin for newly added DOM element:
// Declare new element
var divjRate = "<div><div class='jRate'></div></div>";
// Use plugin on new element
$(divjRate).find('.jRate').jRate({
onSet: function(rating) {
alert(rating);
}
});
// Append new element to container of choice
$(divjRate).appendTo('.fb-jRate');
So I am working with a ckEditor implementation in my project, and I want to provide autocomplete functionality for one of its dialog boxes. I implement the autocomplete functionality by calling a javascript function on a specific input field. However, I am not completely sure on how to obtain the specific input element, as it only appears after I hit a button in ckeditor, so it is no obtainable on document load.
Is there anyway to fire a javascript function upon the loading of a specific div/element? I am trying to use Jquery's $().load function, but it does not seem to be firing. Here is a short example
$(".cke_reset_all cke_1 cke_editor_documentBody_dialog").on("load",function(){
console.log("Successful firing")
//some code here
});
I am not seeing any text in my console, but div with that class name is appearing.
Everytime the dialog box containing the input loads , the following div is created
<div class="cke_reset_all cke_1 cke_editor_documentBody_dialog " lang="en" aria-labelledby="cke_dialog_title_113" role="dialog" dir="ltr">
so I am trying to run my autoComplete script after the loading on this div is done, as the input field I want is nested within it. Any ideas?
The load method in jQuery is an AJAX shorthand method, so it's not what you're after here.
If you want to bind to the load event, you need to use the on method (or bind in earlier versions of jQuery).
Details here: http://api.jquery.com/on/
The load event only applies to some elements, like body, iframe, img, input, script.
In your case, to detect if the input element is present in the page you'll probably have to rely on polling with a setTimeout or setInterval loop. Within the loop, the code will look like:
var inputs=$("div.cke_editor_documentBody_dialog input");
if (inputs.length==1) // do something
Note that the way you wrote the selector in your question is incorrect.
Bind the On method to the parent div, then look for the id/class and carry out your logic/call a function.
$(function () {
$('#parentDiv').on('click' ,'yourselectorhere', function() {
console.log('working');
});
});
I am trying to hide/show a class of elements in a form depending on a drop-down menu choice made by the user. See: http://jsfiddle.net/3FmHK/2/
I am new to js and have two problems, so maybe they are obvious, bear with me.
1) I am modifying by the div id, so only the first element changes (and not in this fiddle for some reason, but it does in the project). However I want all the elements of a class to modify and I haven't been able to make that work. So how do I modify the style="display" for an entire class, rather than a single element?
2) The remove does not work for newly added element, when the form is returned with values in the project, they are removable. Using firebug, the code looks identical for the GET return generated elements vs the user added elements, as far as I can tell. Why does the remove function not work for newly added elements?
I recommend using jQuery for this if you can. You can use the .on() feature to bind actions ot newly created elements and use the class selector to .hide() all classes then .show() the currently selected on by id.
It would look something like this:
jQuery(document).ready( function() {
jQuery(document).on('click', '.classname', function() {
jQuery('.' + jQuery(this).attr('class') ).hide();
jQuery(this).show();
// Or you can use the following to show a specific ID element.
//jQuery('#idtoshow').show();
)};
});
This will hide all elements with the class name. You will need to include the jQuery library before your script. Although I am only using show and hide here, you can use .remove() as long as you bind your action with .on and not just .click. You need .on to bind to newly created elements.
http://api.jquery.com/on/
Hope this helps.
Try:
$(this).parent('div').first().remove();
I'm loading new elements with a form. After the elements are loaded I need to make each one draggable. According to .on doc "Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time."
I've tried oh-so-many variants of .on, .click, etc but so far no luck. I'm currently working with...
$('#parent').on('change', '.thumb', function(event){
alert('loaded');
$('.thumb').draggable();
});
...but, it doesn't attach to the new .thumb element. How can I accomplish this?
Edit: Here's the html...
<input type="file" id="parent" name="files[]" multiple />
<output> //these spans are created after files are selected from 'file'
<span><img class=".thumb" src="..."></span>
<span><img class=".thumb" src="..."></span>
</output>
When you use a plugin that requires binding it's own events and DOM manipulation from within the plugin, delegation methods like on() are useless.
You need to call the draggable() method when you load new elements such as in success callback of ajax.
If you are using load()
$('#myDv').load( url, function(){
/* new html has been inserted now */
/* in case any other active draggables will only search within $('#myDiv') for new elements that need to be called*/
$(this).find('.dragClass').draggable();
})
There isn't enough detail for me to answer this question specifically, so I will attempt to guess what the problem is.
You are binding this function to the event "change" of an element with an id of "parent." The "change" function will only work in certain DOM elements, namely input, textarea, and select. (http://api.jquery.com/change/) This means that the change event will never fire if the element with id "parent" is anything but those three tags.
If this is the problem, I would suggest moving the .draggable() method to the same place you are adding "elements with a form."
Try this:
$('#parent').live('change', '#child', function(event){
alert('loaded');
$('#child').draggable();
});