When the user clicks on my link, the modal element is dynamically generated. I am trying to inject some code into the modal when it is created. My problem is that JavaScript cannot target my modal as it is dynamically generated. How would I do this?
I have tried using on() but I got the error that my modal cannot be found.
$(document).on('click', '.open-modal', function() {
console.log( $('.my-modal') ); //cannot find .my-modal
}
From your comments, f you are following the Bootstrap example then you may mean to use #my-modal (or #myModal if you follow them to the T) since they are identifying the modal by ID instead of class.
EDIT:
The bootstrap modals depend on some preformatted html so I'm not sure how yours is dynamically generated.
Related
I made a website running on an Apache server. The website is only accessed by me. It consists of a drop down list with two options and a "Generate" button. When the button is click, it shows a list of audio elements containing songs. Above each audio element is also a link to the mp3 file itself. I wanted to make a Lightbox
fade in and show the audio element separately when someone clicked on it. I used JQuery to prevent default behaviour when the a tag was clicked, but cannot find a way of only targeting it. This is my problem:
document.addEventListener("click", function(event){
event.preventDefault();});
I have tried changing the document part, but it is showing this error: 'Uncaught TypeError: songPlayer.addEventListener is not a function'. Currently, it is targeting all of the document DOM elements, which is not what I want. Is there any other way of achieving this? Also, does anyone have any tips on making lightboxes? Thanks.
addEventListener needs to be called on a dom element, of soundPlayer has an id of soundPlayer:
var soundPlayer = document.getElementById('soundPlayer');
is what we need,
then we can do:
soundPlayer.addEventListener("click", function(event){
...
In jquery you do the following:
$('#soundPlayer').on('click',function(e){//change #soundPlayer with the css selector of your element
e.preventDefault();
});
I understand when we add popover on an element in html but when we use javascript:
$("#element").popover({ // popover details });
there is no change on #element in html code. How can I refer to all elements with popover when there is no sign of it in html code?
The docs suggest that you add [data-toggle="popover"] to your elements with popovers and refer them through that attribute. However, if you don't do that and just manually initialize the popover, the plugin adds bs.popover data for you (through .data(), not .attr(), which is why you can't see them in the elements).
$("#popover").popover({
title: "Wow"
});
console.log($("#popover").data("bs.popover")); //see the console
http://www.bootply.com/vlpB0I0LcI
As for how to refer to them is bit more complex, as you have to either keep up a list of elements with the popovers like #Tim suggested or just parsing the whole node tree with bs.popover data. Adding the attribute would be much simpler though.
I am trying to click on an image on my webpage and it open a new section on the page that would be created in css and javascript/jquery. I thought about using .addclass() but i am not entirely sure how to go about it. Can anyone give me an example of this being done?
An example by clicking on a element with the id foo and adding a div with the id bar after that element:
$("#foo").click(function(){
$(this).after('<div id="bar">Some content</div>');
});
Of course, there are multiple methods in jQuery which insert content somewhere in the DOM tree, see:
https://api.jquery.com/category/manipulation/dom-insertion-outside/
https://api.jquery.com/category/manipulation/dom-insertion-inside/
There are many ways to do it. As an example, you can simply attach a click event handler to your image, like so:
$('img').click(newSection);
function newSection() {
$('#someDiv').append('<div class="newSection"></div>');
}
so i implemented a bit of jQuery that basically toggles content via a slider that was activated by an <a> tag. now thinking about it id rather have the DIV thats holding the link be the link its self.
the jQuery that i am using is sitting in my head looks like this:
<script type="text/javascript">
function slideonlyone(thechosenone) {
$('.systems_detail').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).slideDown(200);
}
else {
$(this).slideUp(600);
}
});
}
</script>
i was using this as a index type box so there are several products when you click on the <a> tag that used to be an image* it would render a bit of content beneath it describing the products details:
<div class="system_box">
<h2>BEE Scorecard database</h2>
<p>________________</p>
</div>
the products details are wrapped in this div.
<div class="systems_detail" id="sms_box">
</div>
so when you click on what used to be a image* it would run the slideonlyone('div_id_name') function. the function above then first closes all the other divs with the class name 'system details' and then opens/slides the div with the id that was passed into the slideonlyone function. that way you can toggle products details and not have them all showing at once.
note i only kept the <a> tag to show you what was in there i will be getting rid of it.
note: i had an idea of just wrapping the whole div in an <a> tag but is that good practice?
So now what i am wondering is since you need JavaScript to run onclick on a div tag how do you write it so that it still runs my slideonlyone function?
Using obtrusive JavaScript (i.e. inline code) as in your example, you can attach the click event handler to the div element with the onclick attribute like so:
<div id="some-id" class="some-class" onclick="slideonlyone('sms_box');">
...
</div>
However, the best practice is unobtrusive JavaScript which you can easily achieve by using jQuery's on() method or its shorthand click(). For example:
$(document).ready( function() {
$('.some-class').on('click', slideonlyone('sms_box'));
// OR //
$('.some-class').click(slideonlyone('sms_box'));
});
Inside your handler function (e.g. slideonlyone() in this case) you can reference the element that triggered the event (e.g. the div in this case) with the $(this) object. For example, if you need its ID, you can access it with $(this).attr('id').
EDIT
After reading your comment to #fmsf below, I see you also need to dynamically reference the target element to be toggled. As #fmsf suggests, you can add this information to the div with a data-attribute like so:
<div id="some-id" class="some-class" data-target="sms_box">
...
</div>
To access the element's data-attribute you can use the attr() method as in #fmsf's example, but the best practice is to use jQuery's data() method like so:
function slideonlyone() {
var trigger_id = $(this).attr('id'); // This would be 'some-id' in our example
var target_id = $(this).data('target'); // This would be 'sms_box'
...
}
Note how data-target is accessed with data('target'), without the data- prefix. Using data-attributes you can attach all sorts of information to an element and jQuery would automatically add them to the element's data object.
Why do you need to attach it to the HTML? Just bind the function with hover
$("div.system_box").hover(function(){ mousin },
function() { mouseout });
If you do insist to have JS references inside the html, which is usualy a bad idea you can use:
onmouseover="yourJavaScriptCode()"
after topic edit:
<div class="system_box" data-target="sms_box">
...
$("div.system_box").click(function(){ slideonlyone($(this).attr("data-target")); });
You can bind the mouseenter and mouseleave events and jQuery will emulate those where they are not native.
$("div.system_box").on('mouseenter', function(){
//enter
})
.on('mouseleave', function(){
//leave
});
fiddle
note: do not use hover as that is deprecated
There's several things you can improve upon here. To start, there's no reason to use an <a> (anchor) tag since you don't have a link.
Every element can be bound to click and hover events... divs, spans, labels, inputs, etc.
I can't really identify what it is you're trying to do, though. You're mixing the goal with your own implementation and, from what I've seen so far, you're not really sure how to do it. Could you better illustrate what it is you're trying to accomplish?
== EDIT ==
The requirements are still very vague. I've implemented a very quick version of what I'm imagining you're saying ... or something close that illustrates how you might be able to do it. Left me know if I'm on the right track.
http://jsfiddle.net/THEtheChad/j9Ump/
There are a lot of asked questions with almost similar titles with this question of mine, but you know I didn't find an answer.
My simple question is:
I have button, when I click on it, javascript creates modal window
<div class="aui-dialog">
html here...
<button id="closeButton">Close</button>
</div>
just after <body> tag.
I can bind click event of close button with no problem using jQuery live:
$("#closeButton").live("click", function() {
alert("asdf"); // it calls
$("body").find(".aui-dialog").remove();
});
My problem is, I cannot select that dynamically created modal window div by its classname. So that I could call jQuery .remove() method to make close action. Now I know, I must deal with dynamic elements in another way.
What way?
EDIT:
I think it's important to mention this:
I dont' create the modal window myself, I use liferay portal. It has built-in javascript framework AUI(YUI) that creates that modal window. I can just create that close button inside it in its view.
EDIT 2:
Modal window div class attribute value is: "aui-component aui-panel aui-dialog aui-widget-positioned"
Since jquery will read the current DOM-state when page loads:
jQuery( document ).ready(function( $ ) {
it will miss the elements you generate post to page load.
One simple solution is to listen for clicks on document, and filter with the class or element-type that you want to use to execute your code. That way jquery will find new elements generated under document, after page load.
$(document).on("click", '#closeButton', function(){
$(".aui-dialog").remove();
});
Create a reference when you're creating the modal window:
var modalWindow = $('<div class="aui-dialog">html here... <button id="closeButton">Close</button></div>');
// later...
modalWindow.remove();
To your edit:
Get the window via jQuery's parent when the button is inside the modal window:
$('#closeButton').on('click',function() {
$(this).parent().remove();
return false;
});
Many users will come on this page when they want to select some element generated runtime by JQuery and it failed, like me.
The solution is simply approach the root (the parent) of your randomly generated element and then get inner by jQuery TAG selection. For example you generate many TDs of users in a table at runtime, the element having your users list is a table with id tblUsers then you can iterate over runtime generated TRs or TDs as following:
$("#tblUsers tr").each(function(i){
alert('td' + i);
});
further if you have inputs in tds you can go deep in selection as
$("tblUsers tr td input")
Another case could be a randomly generated dialog or popup, then you have to approach its root(parent) and next same selection by TAG as stated above.
You could do a few things, but first, if you are using jQuery 1.7, better use .on(). it has replaced .live() which is deprecated.
if you have no control over the building of the modal but know that the button is a direct child of the modal, then use parent()
$('#closeButton').on('click',function() {
$(this).parent().remove();
return false;
});
if the button is somewhere deep in the parent but has a fixed depth from the parent, use parents() which gets all ancestors of the element, and then filter it to a specific depth. if the close was 2 levels deep, the index of :eq() would be 1.
$('#closeButton').on('click',function() {
//where N is zero-indexed integer, meaning first item of the set starts with 0
$(this).parents(':eq(N)').remove();
return false;
});
another way is to add the handler when the modal is created
var modal = $('modalHTML');
$('#closeButton',modal).on('click',function(){
//modal still refers to the whole modal html in this scope
modal.remove();
});
//show modal
UPDATED:
You can use:
$(".aui-dialog").live('click', function() {
$(this).remove();
return false;
});)
This attach an event handler for all elements which match the current selector, now and in the future.
Please not that this method is depreciated in newer version of jQuery and you should consider using .on() instead of .live().
I found an answer, hope it would be helpful for developers who faced with dynamically generated html with IFRAME inside.
If you have a button (#closeButton) inside that IFRAME, and you want select iframe parent window's dom elements, just add second argument window.parent.document for your selector:
// This functions is inside generated IFRAME
$("#closeButton").on("click", function() {
// body - is your main page body tag
/* Will alert all html with your dynamically
generated html with iframe and etc. */
alert($('body', window.parent.document).html());
return false;
});