Jquery/Javascript: Buttons added dynamically with javascript do not work - javascript

I have a code chunk of html:
<div id="chunk-1" class="chunk">
<div class="chunkText">Text<div>
<button class="addChunk">Click Me</button>
</div>
<script>
$(".addChunk").click(function(){create_chunk(this.parentNode)})
function create_chunk(after_this){
$(after_this).after(chunk_html)
var i = 0
$("div.chunk").each(function(){$(this).attr('id', "chunk-" + i++)})
}
</script>
Now, this works, but only for the .chunk that is statically rendered on the page. When I press the button a second chunk appears, but that button does not work. If I add the html for two or more chunks to be rendered, each one works, but the buttons for the chunks it creates do not. What should I do?

The event handler in the below line attaches the click event to the element matching the selector when you add the handler.
$(".addChunk").click(function(){create_chunk(this.parentNode)})
you can use the live handler to do this. the following code will solve your problem
$(".addChunk").live('click'. function(){create_chunk(this.parentNode)});

Use the "live" jQuery function.
$(".addChunk").live('click'. function(){create_chunk(this.parentNode)});
The problem is that you're binding to a single element. The "live" option will monitor the document for any clicks on elements that have the ".addChunk" class.

replace
.bind()
with
.live()
or even better use
.delegate()
which is in your case:
$('#chunk-1').delegate('.addChunk', 'click', function(){create_chunk(this.parentNode);})
furthermore, go to www.jquery.com and read the documentation.

Related

How to trigger an event on a group of elements?

I have a listener on a group of elements:
$('a.menu__link').on('click',function() {alert('function was triggered');});
One element of which is:
<a class="menu__link menu__link--submenu Main" id="Events" href="#">Events</a>
I want to manually trigger a click on the element. Using Chrome dev tools, the event handler is:
a#Events.menu__link.menu__link--submenu.Main
However, the following code does not trigger the listener:
$('a#Events.menu__link.menu__link--submenu.Main').trigger('click');
I have tried every variation that I can think of, but I cannot find the correct reference to trigger the alert function.
What am I doing wrong?
You can use instead click instead of trigger like this to trigger a click :
$('#div').click();
Read more about click here
Here is a JsFiddle
I encased the trigger in a $(document).ready(function()) and that fixed it.
Kudos to Blazemonger for implying that it was a timing issue.
<script>$(document).ready(function() {
$('#Events').trigger('click');
$('#PastSeminars').addClass('menu__link--current');
});</script></body></html>
The lesson? Just because it is the last thing on the page, when in doubt, use document.ready.
Chrome blocks the click event from being programmatically fired. I'd come up with a new solution such as just calling the needed function wherever you need to trigger it.
You can read more about it here: https://teamtreehouse.com/community/why-does-my-onclick-event-not-fire-on-chrome

Click not working after clearing and appending the html

click not working after i clear and append the html inside a div using jquery.
Here is the html code
<div id="divMain">
</div>
<input id="btn" type="button" value="Clear&Add"/>
Here is the jQuery code
var a = $('<a/>').attr({'id':'aH','href':'#'}).text('Hello');
a.click(function(){
alert('hello');
});
$('#divMain').append(a);
$('#btn').click(function(){
var newA = $('#aH');
$('#divMain').html('');
$('#divMain').append(newA);
});
Here is jsfiddle
Simple click on the alert link in fiddle , it shows an alert.Now click on the Clear&Add button .And now click on alert.It doesn't work.
You need event delegation to bind the event with dynamically added elements. You also need to create elemet with id aH as you have removed the element from DOM without preserving it.
Live Demo
$(document).on('click', '#aH', function(){
alert('hello');
});
You can try adding the globally created a and you would not need to bind click again.
$('#divMain').append(a);
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers, jQuery api
You need to use event delegation:
$('#divMain').on('click', a, function(){
alert('hello');
});
Updated Fiddle: http://jsfiddle.net/W95wV/1/
Click does not work on dynamically created elements in jQuery. In the earlier version of jQuery we could use .live('click') that has been deprecated in the recent versions. Now you can use .on to work better for dynamic elements as Adil said.

Bind an event to a element not created yet jquery

I have a button that is not created until you click in a div.
I need to add an onclick event to that button, but I can't with the .on() method. It doesn't work.
<section class="span9 cont_llens">
<div id="llens"></div>
</div>
The script generates the blocks inside the #llens div. Then if you click a one of these blocks you may see the menu edition, up there it shows up.
So that's the binding I need, onclick to this buttons.
See the example here: http://jsfiddle.net/blackersoul/47YvE/
You can use $.on function for this function specifying the selector (second parameter).
Read http://api.jquery.com/on/
User like $('section').on('click', 'div#llens > button')
The reason why your code is not working because you are canceling the events via stopPropagation at two places. I have commented that in your fiddle and it is working.
See: http://jsfiddle.net/47YvE/4/

jQuery cannot see a dynamic element?

I've a simple code as following:
<html>
<body>
<div id="div1">
<input class="input1" type="text" value="click me 1" />
</div>
<script type="text/javascript">
$('.input1').click( function() { alert('clicked'); });
$('#div1').append('<input class="input1" type="text" value="click me 2" />');
</script>
</body>
</html>
I found that the 2nd textbox, which was appended to the "#div1", didn't get the click respond which is associated to the class "input1".
what am I missing? please advise me, thank you very much.
You should use event delegation with the .on() method...
$('#div1').on('click','.input1',function(...
This places the handler on #div1. When clicks happen inside of it, the '.input1' selector is run, and if the element clicked matches, the handler is invoked.
Or in older versions of jQuery (pre 1.7), use .delegate().
$('#div1').delegate('.input1','click',function(...
jQuery Live Function
: Attach an event handler for all elements which match the current selector, now and in the future.
When you are trying to bind the click event on .input1, it's not available yet, thus the bind will fail.
To fix it, you should use on:
$('#div1').on('click', '.input1', function(){alert('clicked')})
$('.something').click() appends the click listener/callback to anything that is currently in the dom.
When you have elements that were created after dom ready, you can use $('.something').live('click', function() { ... }); to do exactly the same thing for those newly created elements.
But if you're using the newest version of jQuery, use .on(...) because live was recently deprecated.
click and all of the other synonyms for bind only work for elements that exist when the function is called. If you want to also handle ones that may get created in the future, you either have to hook them up when you create them (usually a pain), or use event delegation. Event delegation works by hooking the event on a container of some kind that you're going to put the elements in, and then relies on how events bubble up the DOM from child to parent.
jQuery has excellent support for event delegation in its delegate and (more recently) on functions:
// `delegate` (jQuery 1.4.2 and later)
$("selector for container").delegate(".input1", "click", function() {
// I'll be called when there's a click on anything matching the
// selector ".input1" contained by the container
});
// `on` (jQuery 1.7.0 and later; note that the param order is different from `delegate`)
$("selector for container").on("click", ".input1", function() {
// I'll be called when there's a click on anything matching the
// selector ".input1" contained by the container
});
If the only common container the elements will have is the document itself, that's fine, you can use document as the container. (jQuery has the live function for that, but it's deprecated and it currently just calls on for you.) But in general, the more targeted you can be with the container, the better, from both a performance perspective and a code clarity perspective. For instance, use the form if you're adding form elements to a form; use the table if adding elements to a table. Etc.
Use the jQuery Live function as stated by Achmet.
This is needed because the second input field is created at run-time after the dom has been loaded.

Append element problem

I am creating some elements and appending it, and its working fine but when I want to call any function or want to call any jquery that not work, but when i put that elements directly instead of appending then it works properly. In all to say that appending element does not call any function or anything.
JQUERY CODE:
var cart_content = jQuery($.create('li', {}, [])).append($.create('span',{}, [av_title]),$.create('img', {"src":"images/delete_icon.png", "class":"cart_content", "alt":"delete", "title":"Delete"}, []));
$(".advertise_cart").append(cart_content);
$(".cart_content").click(function(){ alert("Hello"); });
<ul class="advertise_cart" id="advertise_cart_id">
<li>
<span>Inner Content 1</span>
<img src="images/delete_icon.png" class="cart_content" alt="delete" title="Delete"> <!------ On clicking on this will show alert box, but on clicking on appended element will not call alert box or anything ----->
</li>
</ul>
Thanks in advance
The problem you're experiencing is the result of the elements not being present in the DOM when the events are bound. To work around this, you can use delegate() or live():
$('body').delegate('.cart_content','click',
function(){
alert('hello');
});
JS Fiddle demo.
References:
live().
delegate().
Do not use .click function.
Use live function it work for newly added element in DOM
like this :
$(".cart_content").live(function(){ alert("Hello"); });
Using the live function to handle your event might help.
The only thing I'd add is that the live function means that the handler will continue to be applied to content that matches the selector at any point in the future (until and unless you call unbind). That is probably what you want here. If it isn't, you could write could that would add the click handler after a brief delay (say, 1.5 seconds). Or to be a little more sure, you could write code that would check for the presence of .cart_content every 100 milliseconds until it's found, and then add the click handler. So this approach would add the click handler only once. If something caused another .cart_content were added later, the click handler would not automatically be added.

Categories

Resources