Set duplicated buttons to register click events jquery - javascript

I have a div that is duplicated when a button inside that div is clicked. Each duplicated div also contains a button that should duplicate the div. Right now, only the original div "duplicate" button works. I need each button to duplicate the div which contains the button. Here is the my jQuery.
$(function() {
$('.duplicate-button').each(function() {
$(this).click(function() {
$(this).closest('.desking-finance').clone().appendTo('.extra-finance-lease');
});
});
});

The problem is with the execution of this function. It only targets existing elements and not potentially new elements that may be created.
In order to have this function execute on click for every (new or old) div, use live to target them. Here is the refactored code:
$(function() {
$(document).on('click', '.duplicate-button', function() {
$(this).closest('.desking-finance').clone().appendTo('.extra-finance-lease');
});
});
I used document to bind the click handler but try and use a closer parent element relative to the duplicate-buttons. Perhaps some container div.
There was no need for $.each since $(this) will target the targeted element that triggered the event.

Related

How can I either target an Appended element using Jquery or Javascript, or how can I add that appened element to the DOM?

I've looked all over the internet with everyone giving the same answer
$(document).on('click', '#targetID', function() {
// do stuff
});
instead of
$('#targetID').click(function() {
// do stuff
});
This is nice and it works fine, if you have a click event. But within that on click function, the part where it says do stuff, how can I now target an appended element? For instance say I append 2 divs back to back.
<div id="mainDiv"></div>
<script>
socket.on('event', function (data) {
$('#mainDiv').append ('<div class="1st" id="'+data.id+'">one</div>
<div class="2nd" id="'+data.id+'">second</div>');
});
$(document).on('click', '.1st', function() {
//and right here i would like to`enter something like
$('.2nd').css('background-color','yellow');
}
</scirpt>
This however seems not to work because to my knowledge, this element hasn't been added to the DOM. So what should I do? Should i use angular.js for this?
PS I've also tried adding the entire appended content into a variable first before appending that variable. and then using variable.find to find the element within to no avail. The variable only has context within that function, but is null in the on click function. Thanks in advance for any information that broadens my understanding of this.
The delegation of 'on' is correct. Once the div element exists in the dom, clicking should work. My only concern is you have named your classname beginning with a number. Maybe name it with an alpha character followed by a number.
The difference between the 2 is the concept of event binding vs event delegation.
$('#targetID').click(function() { is event binding which works on elements as long as they exist in the markup when the page or document loads.
$(document).on('click', '#targetID', function() { is event delegation which means the event would listen to the document for the click event on the element with ID targetID if it exists in the DOM when the page loads or if it is dynamically added.
So In your case, its event delegation since you are dynamically adding the elements. But in order to make it work, you need to register the listener on the document ready event for the document to listen to the event on the element #targetID
<script>
$(document).ready(function() // Add this
{
socket.on('event', function (data) {
$('#mainDiv').append ('<div class="1st" id="'+data.id+'">one</div><div class="2nd" id="'+data.id+'">second</div>');
});
$(document).on('click', '.1st', function() {
//and right here i would like to`enter something like
$('.2nd').css('background-color','yellow');
});
});
</script>
Here's an example : https://jsfiddle.net/nobcp0L7/1/

How to get Id of hyperlink on click which was appended using jquery

I am appendend a hyperlink to the html page using append() method, It is a list of hyperlinks, and I get all other elements id by this.id, but am not able for the appended row, why this happening? is there any other way to append ??
thanks in advance
It sounds like somewhere in your code you have this:
$("selector for links").on("click", function() {
// Using this.id here
return false; // Since they're links I assume you do this or e.preventDefault();
});
and after that code runs, you add another link, but clicking it doesn't trigger the handler above. That's because the code above hooks the event on the elements that exist as of when it runs; since the link you add didn't exist, its click event didn't get hooked.
You can use event delegation to solve this, by changing the code above to:
$("selector for container").on("click", "selector for links", function() {
// Using this.id here
return false;
});
That hooks click on a container that holds the links, but fires the handler as though the event had been hooked on individual links. So since the event is hooked on the container, you get the event even when you add new links.
Concrete example:
$(document).on("click", "a", function() {
alert(this.id);
return false;
});

jQuery click event problems when selecting by class and <div>

When I access <div> or <p> elements by class with jQuery for a click function, it repeats the event by how many elements are in the array or stack. So, if I have 3 <div> elements on top of each other or next to each other, the one on the bottom, or the one to the right, will go through the event once and the one on the top or the left will go through the event 3 times.
Am I doing something wrong? Or is this not meant to be done with jQuery?
[revision]
sorry if i worded this in a confusing way. here is a link... you will better understand my problem there. just add a couple new elements via the form and click on them.
http://jsfiddle.net/rNj6e/
Now that you've posted a fiddle showing the problem, I can actually answer. The problem is that you bind the click event handler to .dp inside the click event handler bound to #add. So what happens is this:
You fill in the form and click #add, which creates a new element with class dp and appends it
It then binds a click event handler to every element with class dp (there's only 1, the 1 we just added)
You fill in the form again, click #add, which repeats steps 1 and 2, so it binds another click event listener to the first .dp element, and binds one to the new element.
Repeat as necessary, binding more and more event handlers to the existing elements every time you click #add!
To fix this, you need to bind the event handler to .dp outside of the #add event handler. The problem is that you're creating new .dp elements on the fly, so just using .click won't bind to elements that are not in the DOM yet. To solve that, you can use delegate, which binds an event handler to elements matching the selector now and in the future:
$("#preview").delegate(".dp", "click", function(event){
alert(this.id);
});
Here's an updated fiddle.
Try:
$(".some_class").click(function(event){
alert(event.target.id);
}).children().click(function(event) {
return false;
});
This should prevent the click event from bubbling through the children, this happens when you click on the children contained in the div.
You are recieving a blank ID because the target of your clicks is most likely the child you clicked and you haven't given it an ID.
To prove this try...
$(".some_class").click(function(event){
alert(event.target.nodeName);
});
which alerts you the nodeName (the name of the html tag) you just clicked.
Change it to this:
$(".some_class").each( function () {
jQuery(this).click(function(event){
alert(event.target.id);
});
});

remove elements javascript jquery

Im trying to remove a row. But i can't figure it out really.
First of all I've got a button that'll add a new row, that works.
But I want to give the user the possibility to remove the just added row.
The row has an 'div' inside what acts as an deletebutton. But the deletebutton doesn't work?
I'm I missing something?
Greet,
Juki
function addrow() {
$("#container").append("<div id=\"row_added\"><div class=\"deletebutton\" id=\"delbuttonnumber\"></div><div id=\"addedcolor\" class=\"colorcube\"></div></div>");
}
// deleterow the row
$(".deletebutton").click(function() {
rowclrid = "#" + $(this).parent().attr("id");
$(rowclrid).remove();
});
My guess is that you have assigned the click handler before adding the new content, so the handler is not attached to this particular element. You can use .delegate() to listen for events on all elements below a particular parent element, whether or not they already exist:
$('#container').delegate('.deletebutton', 'click', function(){
$(this).parent().remove();
});
This listens for all click events that happen inside the element #container using a feature of the DOM called event bubbling, then checks to see if they happened on a .deletebutton element, and, if so, calls the handler.
Note also the simplified code inside the handler.
I think what you need to do is use the live method. This will add the events for any new item that is added to the DOM, not just the ones that exist when you set the click handler.
// deleterow the row
$(".deletebutton").live('click', function() {
$(this).parent().remove();
});
You also don't need to get the row by getting the ID - it's simpler in the way above.

how to tell jquery to select a parent element, but not its children?

Im using the following click function on an element:
$('#extras').toggle(function() {
$('div#extras').show();
$('div#extras').stop().fadeTo('fast', 1);
},
function() {
$('div#extras').stop().fadeTo('fast', 0, function() {
$(this).hide();
} );
}
);
extras is a div, with many children in it. Some are buttons. Now every time I click one of the buttons, it makes the parent div along with the children disapear.
How do I make it so the click function only fires if the parent is clicked, and not all of its children?
Thanks :)
When you click on a element the click event will be fired for all parent elements. This can be stopped by returning false from the event handler of the children. So you need to have event handlers for all children that shouldn't fire the click event of your div and return false from them. Something like this:
$("#id-of-button-inside-your-div").click(function() {
//Do whatever you need to do
return false;
});
If you hide the parent, you WILL hide the children (decendants) by default.
just for completeness: the selector for the parent of the current element is $(this).parent();
Try to use the children() method.
$('div#extras').children().show();
If a div disappears, all of its content disappears. If you have to make the parent disappear without the children, you should place the children outside in the DOM, and if needed, visually place them inside using CSS.
Try this:
$('div#extras').find('*').click(function(event){ event.stopPropagation(); });
This will make all the elements inside the div to ignore the click event from the div.

Categories

Resources