Im loading a table with DataTables. In each row i creat a button to click, and the value automatically insert into an input in the opener windows. The function i use is this:
$("button").click(function() {
var id = $(this).val();
window.opener.document.getElementById('cliente-nombre').value = id;
window.parent.close();
});
The function is not working with the buttons loaded in the datatable. If i create a button wich load with the page (not when the page is fully load) its works without problem.
I supose this dont work because they are created when the page is fully loaded,
When dealing with elements loaded in after page load, delegate the event handler via on() to a parent element to ensure they respond to the click.
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. This
element could be the container element of a view in a
Model-View-Controller design, for example, or document if the event
handler wants to monitor all bubbling events in the document. The
document element is available in the head of the document before
loading any other HTML, so it is safe to attach events there without
waiting for the document to be ready.
Here I use the document object:
$(document).on('click', 'button', function() {
var id = $(this).val();
window.opener.document.getElementById('cliente-nombre').value = id;
window.parent.close();
});
Try wrapping it in a $(document).ready. This will wait for the page to load before running the code.
$(document).ready(function() {
$("button").click(function() {
var id = $(this).val();
window.opener.document.getElementById('cliente-nombre').value = id;
window.parent.close();
});
});
That way your buttons will be on the DOM before attaching the click handler.
Related
I output some information with xhr request. On this output I also have a button. I want to bind a function (send e-mail) to it, but for some reason I can't.
Obviously I have included jQuery and I do not get any errors in console. I tried few options already!
button html:
$(document).ready(function(){
$('#sendraportemail').click(function(){
var uroemail = $('#uroemail').val();
console.log(uroemail);
});
});
(function() {
$('#sendraportemail').click(function(){
var uroemail = $('#uroemail').val();
console.log(uroemail);
});
});
$('.sendraportemail').click(function(){
var uroemail = $('#uroemail').val();
console.log(uroemail);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-primary sendraportemail" id="sendraportemail">SEND E-MAIL</button>
I tried binding with $('#sendraportemail') or $('.sendraportemail'). What do I do wrong? Help highly appreciated.
You need to use delegated event binding which is necessary for capturing events on elements that are dynamically added after document.ready:
$(document).ready(function(){
$(document).on('click', '#sendraportemail', function(){
var uroemail = $('#uroemail').val();
console.log(uroemail);
});
});
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. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
Source: https://api.jquery.com/on/
I am using massrelevances polling feature. I include an embed code (below) which injects html into the webpage.
embed code from third-party
<div class="mr-space" data-space-id="project-id"></div>
<script src="//platform.massrelevance.com/js/massrel.js"></script>
<script>
massrel.ui.load();
</script>
I want to capture a click event from the html that is injected from their embed code.
The only clicks it will register is when I set it to look within the body, which isn't practical, I need it to register a click within div.option-buttons
var link = {};
link.init = function() {
$('.option-buttons').contents().on('click', function () {
alert('clicked');
});
}
window.onload = link.init;
html that is generated from the embed code above
<div class="option-buttons">
Vote
</div>
Its not clear but you can try
$(document).on('click', '.option-buttons a', function () {
alert('clicked');
});
EDIT
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
You need to use Event Delegation. You have to use .on() using delegated-events approach.
General Syntax
$(document).on(event, selector, eventHandler);
Ideally you should replace document with closest static container.
At the outset, let me be clear I'm not trying to use load() in an Ajax context to load a remote resource.
I'm just trying to bind a function to an object that doesn't exist at page load time, such that I can do stuff to it when it does appear.
I'm using jQuery 1.7
I have a form with class="contact-form").
This form is created on the fly, so it doesn't exist when document.ready() fires.
What I want to do is make some stuff happen when the form is created.
Presumably there should be a "load" or "ready" or some such event fired when the thing is available.
Under previous versions of jQuery I'd have used delegate() or live(); but these have been deprecated, and the current documentation says to use on( "load", handler ) or its shortcut, load().
I'm getting this from https://api.jquery.com/load-event/.
All of the following have so far failed to work:
$(".contact-form").load(function(){
console.log("Hi there!");
});
and
$(".contact-form").on("load", function(){
console.log("Hi there!");
});
and, in a hail-mary based on ideas from Jquery event handler not working on dynamic content,
$(document.body).on("load", ".contact-form", function(){
console.log("Hi there!");
});
Any pointers appreciated.
If you use .load() which is a shortcut for .on('load') called the load event, the matching element (form in this case) must exist at the time the page was loaded. jQuery < 1.7 had a .live() function which would listen for new elements dynamically added to the page, but it was removed in jQuery 1.7 for various reasons, performance being a major one.
Other options
jQuery LiveQuery is a plugin that sounds like it will do exactly what you're looking for.
https://github.com/brandonaaron/livequery
jQuery Entwine will watch for new DOM elements using livequery, but also allows you to create DOM elements and use them as full objects with their own methods defined.
https://github.com/hafriedlander/jquery.entwine
More info from jQuery's .on() docs
You can use Delegated events to create a click handler which will fire when an element is dynamically added to your original selector (typically a container), such as:
$( "#dataTable tbody" ).on( "click", "tr", function() {
alert( $( this ).text() );
});
Now, when a new <tr> is added dynamically, it will have the click handler bound to it. However, there is no event for the actual loading of an element into the DOM.
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.
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. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
Why do you need an event at all? If the form is being added dynamically then run what you need to at the time
var form = '<form class="contact-form"></form>';
$('body').append(form);
console.log("Hi there!");
This method is a shortcut for .on( "load", handler ).
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
For example, consider a page with a simple image:
<img src="book.png" alt="Book" id="book">
The event handler can be bound to the image:
$( "#book" ).load(function() {
// Handler for .load() called.
});
As soon as the image has been loaded, the handler is called.
Now put that inside a ready handler
$( document ).ready(function() {
// onload functions here
});
I'm having a lot of issues with events triggering in my colorbox popup. Currently, there is a backbone view taking care of a user profile page. There is a gallery of photos, that when clicked, opens a colorbox that contains the photo, as well as comments, comment input form, and like buttons.
The html I put into the colorbox is a hidden div on the template itself. Everything displays just fine, but clicking things don't trigger anything. I figured I would try to attach the event handlers to the html I pass into the colorbox function, since I'm guessing the pop up colorbox is not considered to be in the backbone view's dom. The function is below, which the Backbone view triggers of a click event on an img. The var photoBox is the html I want to be displayed in the colorbox. I tried to attach event handlers to the photoBox, but to no avail.
popColorbox: function(event) {
var photoID = $(event.currentTarget).parent().attr('data-id');
var photoBox = $("#inline_example" + photoID).parent().html();
$(photoBox).on('click', '.unlike', function(){
console.log("hello");
alert("hello");
});
$(photoBox).on('click', '.like', function(){
console.log("hello");
alert("hello");
});
$.colorbox({html: photoBox});
}
Your first assumption as to why the events aren't being triggered is correct. In backbone view's the events are delegated to their root el, as such since the colorBox's elements are not children of the view's el its events aren't being triggered.
The reason why your events aren't being fired when you try binding directly to the photoBox I think is because the colorBox plug-In expects a string of html which it uses to build up it's html (as opposed to just attaching the nodes you pass in).
In order to trigger your events you will need to bind them to some existing higher element on the DOM, in this case you might need to go up to the document.
$(document).on('click', '.unlike', function(){
console.log("hello");
alert("hello");
});
$(document).on('click', '.like', function(){
console.log("hello");
alert("hello");
});
Maybe here the event listener is added on html rather than a selector. Please look at jQuery documentation on adding an event listener. http://api.jquery.com/on/
I have a document with:
<button class="route" data-route-url="/about">About</button>
About
<div id="page-content">
</div>
$('.route').click(function() {
console.log('.route.click()');
var url = $(this).data('route-url');
$('#page-content').html('loading...');
$.get(url, function(data) { $('#page-content').html(data); });
return false;
});
It works perfectly until this point, and loads the about page.
The about page bring another button that also calls "route":
<button class="route" data-route-url="/contact">Contact</button>
But, when I click on it nothing happens, and I also dont get the console.log message, so seems that the page, that was first loaded inside the div-content can not see the parent function called route, is this working as expected?
How am I supposed to make this work?
You can do this by using Event Delegation with .on() since your button is added dynamically to DOM, The event registered before doesnot apply to the newly added button. SO you need to go with Event delegation, i.e attach the event to the parent container (which exists already) or document element(as i have used in the code) and set up for delegation once an element with the class '.route' is available anytime now or in future.
$(document).on('click','.route' ,function() {
console.log('.route.click()');
var url = $(this).data('route-url');
$('#page-content').html('loading...');
$.get(url, function(data) { $('#page-content').html(data); });
return false;
});
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. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document.