This question already has answers here:
Jquery dynamic button : how to bind to exisitng click event by class
(2 answers)
Closed 9 years ago.
I have a button which calls a function via data-bind and generates a new button.
self.submitNewPopUp = function(data, event) {
var butnId = event.srcElement.form.id.replace('style-', '');
var styleButton = $('<input/>').attr({type: 'button', value: data.styleData, id: butnId});
styleButton.onclick = function() {
alert("blabla");
};
$("#showButtons").append(styleButton);
$('#' + event.srcElement.form.id).hide();
};
But the new button has no click event. How to do it?
You'd assign a click event listener to an ancestor of the button using jQuery's on() method. For instance, if your markup was:
<div id="showButtons">
<input type="button" />
</div>
You'd use:
$('#showButtons').on('click', 'input[type=button]', function() { ... });
styleButton button is a jQuery object, not a dom element so it does not have a onclick property. You need to use the click(function(){}) event registration method to register the event handler
styleButton.click(function() {
alert("blabla");
});
Use jquery.on() for the dynamic created elements
$("#div").on("click", "button", function(event){
alert($(this).text());
});
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I need to attach an event to a dynamically created element. With jQuery I can archive this by using the following code:
$("body").on("click", ".my-element", function() {});
And if I added a new .my-element, it automatically got the event attached.
I'm not creating the elements via document.createElement("div");, but I'm using pjax to reload just some parts of the page, so the main JavaScript file just loads one time, for that reason events need to be attached dynamically.
How can I achieve that with vanilla JavaScript?
A pure JavaScript version of your jQuery example
$("body").on("click", ".my-element", function() {});
would be:
document.body.addEventListener("click", function (e) {
if (e.target &&
e.target.classList.contains("my-element")) {
// handle event here
}
});
See example below.
const addTestElements = () => {
var el = document.createElement("p"),
node = document.createTextNode("Test element, class 'my-element'");
el.classList.add("my-element");
el.appendChild(node);
document.body.appendChild(el);
el = document.createElement("p");
node = document.createTextNode("Test element, class 'test'");
el.classList.add("test");
el.appendChild(node);
document.body.appendChild(el);
}
document.getElementById("add").addEventListener("click", addTestElements);
document.body.addEventListener("click", function (e) {
if (e.target &&
e.target.classList.contains("my-element")) {
console.clear();
console.log("An element with class 'my-element' was clicked.")
e.target.style.fontWeight = e.target.style.fontWeight === "bold" ? "normal" : "bold";
}
});
<button id="add">Add element</button>
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I've got some cards (forms) created with ng-angular based on Array list.
On each card i have onClick event which doesn't trigger. If I copy paste the function code on browser console, all events work ! I guess that events aren't bind when the DOM is fully loaded.
These are my functions :
$('.floating-open').on('click', function () {
var $this = $(this);
$this.parents('.clickable-button').addClass('clicked');
$this.parents('.clickable-button').next('.layered-content').addClass('active');
setTimeout(function () {
$this.parents('.card-heading').css('overflow', 'hidden');
}, 100);
});
$('.floating-close').on('click', function () {
var $this = $(this);
$this.parents('.layered-content').prev('.clickable-button').removeClass('clicked');
$this.parents('.layered-content').removeClass('active');
setTimeout(function () {
$this.parents('.card-heading').css('overflow', 'initial');
}, 600);
});
Thanks in advance for your help
try to bind click event like below
$(document).on('click', '.floating-close', function(event) {
//your code
}
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I am facing a problem with on(). Here is my code:
<span class="add" id="id_foo" >add this stuff</span>
$(".add").on('click', function() {
$.post("/toto.com/add.php", { trainning: this.id }, function() {});
$(this).html("Remove this stuff");
$(this).removeClass("add").addClass("remove");
//alert($(this).attr("class"));-->give the good class
});
$(".remove").on('click', function() {
//doesn't work
$.post("/toto.com/remove.php", { trainning: this.id }, function() {});
$(this).html("add this stuff");
$(this).removeClass("remove").addClass("add");
});
The selector for the class remove doesn't recognize it whereas when I click on the button with the add class, the class is changing. Do you know what the problem is?
Thank you for your help!
You need to use delegated event handlers as you're dynamically changing the classes the handlers are attached to. Try this:
$(document).on('click', ".add", function() {
$.post("/toto.com/add.php", { trainning: this.id });
$(this).html("Remove this stuff").toggleClass("add remove");
});
$(document).on('click', ".remove", function() {
$.post("/toto.com/remove.php", { trainning: this.id });
$(this).html("add this stuff").toggleClass("remove add");
});
Depending on the location of the script tag this JS code is in you may also need to wrap your code in a document.ready handler. If it's just before the </body> tag it will work fine, if it's in the head, place it inside $(function() { /* your code here */ });
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
jQuery click not working for dynamically created items [duplicate]
(8 answers)
Closed 7 years ago.
I'm trying create a list of Messages a user can type in an textarea on the site and delete any of them using a button he automatically creates with each message.
My idea is that I create a div in which I first put the message of the user in and then prepend the button with the same ID of the div; This way I call the ID of the button and remove all elements with the same ID.
<script>
var theButtonId = 1;
$(document).ready(function() {
$('#commentButton1').click(function() {
var toAdd = $("textarea#commentTextarea1").val(); //Content to add
var theId = "dieButtons"+theButtonId.toString(); //creating unique ID
// Adding first Div
$('#targetField').append(
$('<div />', {
id: theId,
}));
// Adding content
$('#'+theId).append(
$('<div />', {
text: toAdd
}));
//(-----1-----)Adding Button
$('#'+theId).prepend(
$('<button />', {
type: 'button',
id: theId,
class: 'commentButton2',
text: "-"
}));
theButtonId++;
});
});
//Button Command
$(document).on("ready", function(){
//(-----2-----)
$('.commentButton2').on("click", function(){
var thisId = $(this).attr("id");
$("#"+thisId).remove();
});
});
</script>
It perfectly lists the elements in the #textfield
I added a button directly in my HTML code which deletes certain divs, as well as itself using the code above. This is why I know that the Problem is that the created Buttons at (-----1-----) don't react to the command in (-----2-----)
I already tried to create an Input of type button and put a .click function instead of .on("click", [...]).
$(document).on('click', '#buttonid', function() {
});
Use event delegation on dynamically created elements
DOCUMENTATION
Working fiddle
Try to use :
$('#targetField').on("click",'.commentButton2', function(){
Instead of :
$('.commentButton2').on("click", function(){
It should work.
This question already has answers here:
How do I detect a click outside an element?
(91 answers)
Closed 9 years ago.
The problem was that I need a "onClickOut"-Event.
For example:
You have a DIV viewing on hovering (onMouseOver) some Button or what ever.
If you click outside the element it needs to hide, but if you say $("body").click it also will be hidden when you click into the element itself. :/
Now I listen the mouseposition and when mouseleave() I set a var on clicking into my element. In the next step I listen a generelly click-event (body) but I ask if the var was set. If not it has to be a click outside my element, so I can hide my element.
I hope you can use it:
$("#schnellsuche_box").mouseleave(function() {
var inside;
$("#schnellsuche_box").click(function() {
inside = true;
});
$("body").click(function() {
if(!inside) {
$("#schnellsuche_box").hide();
}
});
delete inside;
});
You do that by listening to a click on the document level, and inside the event handler you check if the clicked element was #schnellsuche_box or any element inside #schnellsuche_box by using closest(), like so :
$(document).on('click', function(e) {
if ( ! $(e.target).closest('#schnellsuche_box').length )
$('#schnellsuche_box').hide();
});
FIDDLE
You need to stop the #schnellsuche_box click event from bubbling up to the body click event (that's default event propagation) by doing return false:
$("#schnellsuche_box").click(function() {
inside = true;
return false;
});
Try this:
$("body").click(function(e) {
var $target = $(e.target);
if (!$target.is('#schnellsuche_box') &&
!$target.parents('#schnellsuche_box').length) {
alert('outside');
}
});
$("#schnellsuche_box").on("click",function(event) {
event.preventDefault();
event.stopPropagation();
});