This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
I want to create after every container a click function. It had worked but not anymore. When I want to create the event, he don't recognize the container because in debugger I can see he's going over the box of code.
// Decide list order, load the thumbnail for each publication.
var place = "first";
$('#archive').prepend('<div class="container" id="'+entry.publicationID+'"></div>');
$('.container:' + place).append('<div class="thumb"></div>');
$('.thumb:' + place).css("background-image", 'url(' + entry.thumbnailURL + ')');
$('.thumb:' + place).css("filter", 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + entry.thumbnailURL + ',sizingMethod="scale")');
$('.thumb:' + place).css("-ms-filter", 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + entry.thumbnailURL + ',sizingMethod="scale")');
// Load the publication title below each thumbnail.
$('.thumb:' + place).after('<div class="title"></div>');
$('.title:' + place).append(entry.publicationName);
// Load the publication startsdate & enddate.
$('.title:' + place).after('<div class="date"></div>');
$('.date:' + place).append(sdate + " tot " + edate);
// Set up publication links.
$('.container:' + place).click(function(){
loadPub(entry.publicationID, entry.publicationName);
setActive(entry.publicationID);
//Change css of current element
});
http://api.jquery.com/on/ this will help you. Basically attach the click on the outer container of the div or box you dynamically create and check the target which is done by "on" api in jQuery
If you are loading these elements dynamically, you'll want to use the .on and delegate events so that elements loaded after the DOM has loaded will know to attach click handlers.
Below is an example of me using the .on(). I declare my parent container in the selector and the specific elements I want to delegate event listeners to. In this case, I can specify the pseudo-class :first and jQuery is smart enough to know to only do it to the first element.
$(document).ready(function(e) {
for (var i = 0; i < 10; i++) {
$('#container').append('<div class="element">Element ' + i + '</div>');
}
$('#container').on('click', ':first', function(e) {
alert('hello! this should only work on the first element!');
});
});
.element {
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
Related
I'm using FullCalendar that's filled with events that's populated from a mysql database. I'm using the eventClick function of FullCalendar to send the contents of the event to a separate div so I'll be able to print out the events that I've clicked.
Using this code below, I'm able to click on the event and it adds the lines that I need to the div, but it'll add duplicates because there's nothing stopping it from doing so as I'm just appending each event when I click on one.
// FullCalendar eventClick function
eventClick:function(event){
$(document).ready(function(){
document.getElementById("event_info").innerHTML += event.description + "<br>" + event.start + "<br>" + event.end;
});
}
// div where the information will print
<div class="col-sm-3" id="event_info"></div>
So I want to be able to click on a calendar event & send it to the div, but also check to see if the event has already been added and if it has, remove it. Finally, I'm looking to group the events by the description name when clicked.
I'm not sure where to start with adding those so any help or direction would be much appreciated. Thanks for your time and feel free to yell at me if I didn't explain something very well.
Why not simply include something like a class or data-attribute once you first add the event to the div, and then check if that is present, before adding another event?
var target = document.getElementById("event_info");
var isAlreadySet = target.getAttribute('data-eventAlreadySet');
var newHTML = event.description + "<br>" + event.start + "<br>" + event.end";
if (!isAlreadySet) {
target.innerHTML += newHTML;
target.setAttribute('data-eventAlreadySet', "true");
} else {
// your code here if the event is already set
// to replace the former event, use something like :
target.innerHTML = newHTML; // replaces the HTML
//instead of :
target.innerHTML += newHTML; // adds to the existing HTML
};
you need to check the div innerHtml before appending a new text. Please try the following code:
// FullCalendar eventClick function
eventClick:function(event){
$(document).ready(function(){
if($("div#event_info:contains("+event.description+")").length <=0)
{
document.getElementById("event_info").innerHTML += event.description + "<br>" + event.start + "<br>" + event.end";
}
});
}
My whole div is clickable and will change the page. However, inside my div, I have an element that is also clickable, but it should be prioritized sincee it stays on the page.
Basicly, i'm working on a webshop. clicking on a div will go to a new page with the requested data. However, the div includes a clickable image that adds the item to the wishlist.
In the code below, child refers to my whole clickable div, whereas my wishElement is the clickable image to refer to my wishlist.
$('#' + wishElement).click(function() {
window.location.href = "http://website.com/index.php?wish=" + child;
});
$('#' + child).click(function(){
window.location = "http://website.com/item.php?item=" + child + '&name=' + itemname + '&link=' + link;
});
Use event.stopPropagation(); to stop your child event from bubbling up:
$('#' + child).click(function(ev){
ev.stopPropagation();
window.location = "http://website.com/item.php?item=" + child + '&name=' + itemname + '&link=' + link;
});
My problem has been solved by the post coded above, however, the
ev.stopPropagation();
has to be inside my wishElement in order to work.
So thanks for the help!
I am referencing one element on an index page hidden initially and then showed with jquery on an index.html page. Can't explain why the first ones doesn't work, even if it should, but the last one does. I am getting the id of a pressed button "id='edit1'...2...3..etc" Thank you!
//why this doesn't work and the next one does???
/*$('.edit-btn').click(function(){
var id = $(this).attr('id');
console.log("btn1:", id);
});
$('.edit-btn').on('click', function(){
var id = $(this).attr('id');
console.log("btn1:", id);
});
*/
var id;
$("body").on("click",".edit-btn",function(){
id = (this.id).replace("edit","");
UPDATE:
The containers are hidden and shown using this function:
function hideWindowsAndShowOneWindow(sWindowId) {
$('.wdw').hide(); //fadeout 500
$('#' + sWindowId).show(); // fade in 500
}
So the div container, I am trying to reference by id was hidden after the page was loaded or maybe before the page is loaded. My guess is after the page is loaded...
The HTML:
<div class="wdw" id="wdw-events">
<h4>Events text</h4></br>
<div id="content"></div>
<h4>Edit Events</h4></br>
<div>
</div>
It is added/injected after the page was loaded with this js script, but still what has the last method special, just referencing through the document down to the id attribute of the button:
finalEventsLS.forEach(function (item) {
var date = item.date.day + "/" +item.date.month + "/" + item.date.year;
$('#content').append("<ul><li>" +
"Event nr.: " + item.id + " " +
"Name: " + item.name + " " +
"Topic: "+ item.topic + " " +
"Speaker: "+ item.speaker + " " +
"Date: " + date + " " +
"</li><button class='edit-btn' id='edit" + item.id + "'>Edit</button>
</ul>");
})
It's hard to tell, since you've only shared your jQuery. Update with your HTML please.
If you are referencing an element which was added to the DOM after the initial page load, .click will not work, because it only looks for elements initially loaded into the DOM. Instead, you would use the .on method, which looks for elements added to the DOM both before and after initial load.
UPDATE:
I should have looked closer. The second snippet of code that didn't work, but used the .on method, most likely didn't work because you are still trying to access the .edit-btn element, which at this point I'm assuming was added after page load. The code snippet that does work, is accessing the body element first. I will try to find and update with a better explanation, but the .on method still needs to find a element that existed in the DOM initially. From there, it can climb down the tree to find .edit-btn element.
This question already has answers here:
jquery click event not firing on dynamically created div
(3 answers)
Closed 8 years ago.
I created a button tag inside my javascript
value = '<button id="structure_' + arrayCodStructure[j] + '" class="ui_btn" >' + arrayCodStructure[j] + ' </button><br></br>';
and then appended to an existing div this way:
$("#listContent").append(value);
My purpose is to get button's id when I click on the specific and tried the below code with no luck.
$("#listContent.ui_btn").bind("click".function() {
var id = $(this).Attr('id');
alert("id: " + id);
}
Any solution?
selector on #listContent works but it is not what I need.
Try to use event-delegation at this context and the selector that you have used is also wrong,
$("#listContent").on('click',".ui_btn" ,function() {
var id = this.id;
alert("id: " + id);
}
At the moment I'm building a list using the following code:
$('<li id="li' + jJob.Id + '"><div style="width: 98%; background-color: #9E7BFF; colour: #000000">' + jJob.Type + ' ' + jJob.AddressClean + ' (' + jJob.Status + ')' + '</div></li>').click(function(e) { ShowStatus('job ' + jJob.Id + ' is available'); UnassignJob(jJob.Id); $(this).remove(); }).bind("contextmenu", function(e) { alert('li' + jJob.Id); return false; }).appendTo('#assignmentList');
This works as previously required. However I need to be able to add another a link which will show another menu allowing various options. The problem is that I've attached the click event to the div. How can I attach it only to the a link?
Create li
Create div
Create a link with click event
Create another a link click event
Append li to #assignmentList
Mark
You want to append your onclick event to your <a> link inside the li correct?
One option would be to remove the
.click(function(e) { ShowStatus('job ' + jJob.Id + ' is available'); UnassignJob(jJob.Id); $(this).remove(); })
And instead place this in your link, e.g.
' stuff '
Where NewClickEvent is defined as
function NewClickEvent(jobID)
{
ShowStatus('job ' + jobID + ' is available');
UnassignJob(jobID); $(this).remove();
}
Note- you may have to fiddle this a bit to get $(this) to work as it did previously... not sure what object it will bring back currently.
You could use either the href attribute as shown, or add an onclick attribute to the link.
Hopefully this should give you at least some inspiration :)