Bind to events inside dynamically created iframe - javascript

I need to bind to an event (say a click on an arbitrary <input>) inside an iframe that is created dynamically after the user performs a certain action. The code that appends the iframe AND the code inside the iframe is not mine and I cannot change it in any way (this is a CMS admin panel).
How can I listen to the events using jQuery 1.6 (again, this is not my choice, I'm stuck with it). I thought delegate() might be what I want:
$('body').delegate('iframe input', 'click', function(e) {
alert('bingo?');
});
But the above does not alert when an input is clicked. The below, however, works as expected:
$('body').delegate('input', 'click', function(e) {
alert('bingo?');
});
But this is outside the iframe.
The src of iframe points to the same domain, obviously.
Any help or just a prod in the right direction is greatly appreciated.

This 'iframe input' does not selects input elements inside the iframe.
You can bind the event like
$('body iframe').contents().find('input').bind('click',function(e) {
alert('bingo?');
});
I think You can also use something like
$('body iframe').contents().find('body').delegate('input','click',function(e) {
alert('bingo?');
});
To detect if the iframe has been fully loaded, use the method described in this answer
https://stackoverflow.com/a/5788723/344304
Add In the main/parent document:
function iframeLoaded() {
$('body iframe').contents().find('input').bind('click',function(e) {
alert('bingo?');
});
}
Add In the iframe document:
window.onload = function() {
parent.iframeLoaded();
}
Or use
$('body iframe').load(function(){
$('body iframe').contents().find('input').bind('click',function(e) {
alert('bingo?');
});
});

Related

trigger click event of the span tag using Javascript

I'm trying to trigger click event on tag inside the div tag.here is my code
$(document).ready(function () {
$("#span").on('click',function(e){
console.log("clicked in link");
});
});
and here is the html structure (this is a PDF-tron Pdf viewer)
but , it doesn't work. How could I trigger the click event using pure Java script?
Thank you.
The issue is that span is a tag name, not an ID, so instead of $("#span") you should do $("span"), but be careful, there might be other span elements there as well.
"How could I trigger the click event using pure Java script?"
The trick for PDFTron WebViewer is that it reners the document in an iFrame.
So, to access the iframe DOM element, you can do this in the WebViewer constructor, for example:
Webviewer(
{
/// ...
},
document.getElementById('viewer')
).then((instance) => {
instance.iframeWindow.document.querySelector('put_your_selector_here').addEventListener('click', () => {
console.log('clicked');
});
});
Use jQuery.click:
$("span.link").click()
#Spectric has half of the answer really
$("span.link").click()
will click on the span but you incorrectly set the click function
$("#span").on('click',function(e){
the # is for ids not for all elements. So it should be changed to
$("span").on('click',function(e){
or better yet to be more specific like #Spectric said
$("span.link").on('click',function(e){

Click event doesn't fire when parsing external html

I have a project where I need to load html from an external file and add it to an existing div element.
It works great, except that the .click() events never fire when clicking on the desired icon in the generated html.
Code that loads the html:
$.each(data, function (index, review) {
let html = $.parseHTML($.trim(review));
$(html).appendTo($items);
});
Root element of the loaded html is a class named "lc-rating-wrap".
The js that doesn't fire on click:
$(".lc-rating-wrap > .vote-wrap > .do-vote-wrap > .icon").click(function () {
//doStuff
});
I guess it has something to do with that the elements isnt there when I load the js file?
Am I using parseHTML() correctly?
Your content is dynamic, but your event is binded only for existing elements. Change it to be $(static).on(event, dynamic, callback):
$(document).on('click', ".lc-rating-wrap > .vote-wrap > .do-vote-wrap > .icon", function () {
//doStuff
});
Please use delegate instead click.
$( "#parent" ).delegate( ".icon", "click", function() {
//dostuff
});
Parent is a element which you using to generate your elements (inside).
So it cannot be generated dynamicaly.
use jquery click event delegation. see https://learn.jquery.com/events/event-delegation/
Bind event to an parent element already found in your page when js is binding click event. Use .on("click", "your selector", function(){})

jQuery Child Event Handling

I have a container element. The element may or may not have anchor tags in it. I want to listen for click events within that element. I want to handle each click only once, but I want to do something different if an anchor tag is clicked.
Issues that I've run into:
Listening at the container element level doesn't capture the anchor tag clicks: $('#ID').on('click', myFunction);
Listening to every child in the container ends up firing multiple events: $('#ID').find(*).on('click', myFunction);
How do I accomplish this?
This should work:
$('#ID').on('click', function(e) {
if ($(e.target).closest("a").length) {
anchorWasClicked();
} else {
somethingElseWasClicked();
}
});
You can check the target of the click. And as you seem to be trying to enable the click just once for every element within the container, you should then use .one():
$(function() {
$("#container").children().one("click", function(e) {
e.preventDefault(); // For testing purposes.
if ($(e.target).parents().is("a") || $(e.target).is("a")) {
// Anchor.
}
else {
// Others...
}
});
});
Demo
That's an improvement to the example I've posted in the comments previously.

remove all links from within div

I've embedded a custom ggl map within a container div using javascript (not the google iframe), and a div to display the map within the first/original container div. I need to deactivate all links within either div so that the links in the embedded map are not clickable.
I've tried the following JQuery solution but it doesn't seem to work:
<script>
$("#map_canvas a").click(function(e) {
e.preventDefault();
});
</script>
Then I've tried the following CSS solution but it blocks the user's ability to pan the map.
pointer-events: none;
How can I enable user interactivity with the map while preventing anchor links from working within the embedded map? Thanks!
I would guess your first problem is that those links are created dynamically. So, when you call $("#map_canvas a"), there are no a elements to bind to. You might try the delegated syntax of bind(). Assuming #map_canvas exists when your script is called (and I would recommend putting your code in a ready block):
$( function() {
$('#map_canvas').on('click', 'a', function() {
// return false will preventDefault and stopPropagation in jQuery
return false;
});
});
You should use the following code, if there are elements nested inside the tag. Otherwise they will be removed aswell.
$(document).ready(function() {
$("#map_canvas a").removeAttr("href");
});
Or you can do something like this.
$('#map_canvas a').click(function () {return false;});
This will remove the <a> elements themselves. I don't know if that's what you want:
$("#map_canvas a").remove();
But as has already been said, you have to wait for the DOM to be ready because those links are probably automatically generated and are not part of the initial, static layout, and therefore are not bind to the DOM.
So, this could do the trick (it will be executed only when the DOM is ready) :
$(document).ready(function() {
$("#map_canvas a").remove();
});
If you dont want to remove the <a> elements in themselves and just deactivate them, try:
$(document).ready(function() {
$("#map_canvas a").on('click', 'a', function() {
return false;
});
});

Dynamically added javascript is not working, but static code works fine?

Here is what I'm doing... I have a textbox that users type something in and click an add icon. This fires some jquery code that adds the item they typed into a span within a "content" div. The generated code has a delete icon that appears on hover and when clicked it should make the span disappear. This works if the code is on the page already (before document load) but if it's dynamically created, it breaks the delete on click functionality.
Here is a JSfiddle so you can see it in action: http://jsfiddle.net/WF32y/
What can I do to fix this? I essentially want to do what happens on here (stackoverflow.com) when you enter tags to a new question.
Use event delegation for dynamically added elements by changing this:
$('a.delete').on('click', function(e) {
Into this:
$(document).on('click', 'a.delete', function(e) {
Fiddle
.on() Direct and delegated events reference
Also, concerning performance, you can attach the handler to a closer ancestor of the dynamically added elements than the document (e.g. a static wrapper element).
You can easily do it with delegate. In your case:
$('#container').delegate('a.delete','click', function(e) {
e.preventDefault();
taskID = $(this).closest('.task')[0].id;
$(this).closest('.task').fadeTo(300, 0, function() {
$(this).animate({
width: 0
}, 200, function() {
$(this).remove();
});
});
});
And by the way FYI:
// jQuery version 1.4.3+
$('#container').delegate('a.delete'...
// jQuery 1.7+
$('#container').on('click', 'a.delete', function(e) {
it is faster and more propery way than:
$(document).on('a.delete'...
or:
$('body').delegate('a.delete'...
or:
$(document).delegate('a.delete'...

Categories