I am trying to handle the click event using jQuery
on upload success, I am creating the following using jQuery:
$("#uploadedImage").append( "<div class='img-wrap'>
<span class='deletePhoto'>×</span>
<img data-id='"+files[i]+"' src='"+asset_url+"uploads/ad_photo/"+files[i]+"'>
</div>
<span class='gap'></span>");
and for handling click event for the above created div's I have written this:
$('.img-wrap .deletePhoto').click(function() {
var id = $(this).closest('.img-wrap').find('img').data('id');
alert(id);
});
the above code is working properly and creates all div, but when I click on the deletePhoto span. no jQuery alert is showing.
Any help or suggestion would be a great help.
Thanks in advance
delegate the event and change as suggested:
$("#uploadedImage").on('click', '.deletePhoto', function() {
You have to delegate your event to the closest static parent #uploadedImage in your case which is available on the page load like the container which holds the newly appended div and image.
although $(document) and $(document.body) are always available to delegate the event.
It is better to use on() when you create new element after DOM has been loaded.
$(document).on('click', '.img-wrap .deletePhoto', function() {
});
You are creating your element dynamically that is why you would need .live()
but this method is deprecated in newer version.
if you want to use jquery 1.10 or above you need to call your actions in this way:
$(document).on('click','element',function(){
`your code goes in here`
})
try this:
$(".img-wrap .deletePhoto").on('click', function() {
});
You can change a little in your code.
$(".deletePhoto").off("click").on("click",function(){
//Your Code here
});
First check in debugging mode that you get length when your code is going to bind click event and another thing bind event must written after that element is appended.
And Also check css of your element (height and width) on which you are clicking and yes
$(document).on('click','Your Element',function(){
//your code goes in here
});
Will works fine
use delegate:
$('#uploadedImage').on('click','.img-wrap .deletePhoto',function() {
var id = $(this).closest('.img-wrap').find('img').data('id');
alert(id);
});
see details delegate and .on here
Related
I am trying to make an element disappear when clicked, the elements are dynamic.
$("#toast-container").on("click", "div.toast", function() {
$(this).fadeOut("fast", function() {
$(this).remove();
});
});
I have tried the code with just $(this).remove() and it works but using fadeOut it doesn't. I have no idea why and it looks absolutely fine to me
I have a easy solution.
HTML
<div id="toast-container">
<div class="toast">
Click Me
</div>
</div>
jQuery
$("div.toast").click(function(){
$(this).parent("#toast-container").fadeOut('slow');
// run your another event.
})
Check my live demo on jsfiddle
well when adding elements dynamically to DOM tree i think your events may register at creation of the page but when you add an element dynamically you should use another jquery function which is called delegate
see the documentation
What is this?
"div.toast"
If your div class is "toast", it should just be ".toast" (it will work with the div.toad, but syntactically, this is not really correct.
That said, your function works fine when I drop it in a fiddle. Are you certain that you are not getting any console errors perhaps related to another feature/function? Check your console.
I have a link to slide down a div as follows.But initially this link has no onclick handler, which I am inserting using the jQuery code.
Show Div
Now the following is the jquery code
//id comes from a loop which runs from 1 to 15
$("#Link_"+id).attr('onclick','$(\'#Div_'+id+'\').slideToggle(\'slow\');');
$("#Link_"+id).attr('style','color:white;');
$("#Link_"+id).attr('value','0');
The last two lines are inserting attributes but the first line is not working and also I am not getting any error.I am using jQuery 1.4
EDIT
Now the surprise,I just by luck tried it,
the first line is working in jquery 1.9.Why?
You can't add a click handler like that, try this instead:
$("#Link_"+id).live('click', function(){
$('#Div_'+id+'').slideToggle('slow');
});
Try binding it this way:
$("#Link_"+id).on("click", function () {
$('#Div_'+id+).slideToggle('slow');
});
as you are using jquery 1.4. You would be needing live instead of on
$("#Link_"+id).live( "click", function() {
$('#Div_'+id+).slideToggle('slow');
});
I would recommend using .click() instead.
$("#Link_"+id).click(function(){
$('#Div_'+id).slideToggle('slow');
return false;
});
To answer the edit: jQuery 1.9 checks if you are trying to set an event handler and adds the handler instead of setting an attribute. jQuery 1.4 doesn't have such a check. (I looked at the source)
I'm using underscore to create some elements and appending them to a div with jQuery.
At the bottom of the page I'm using jQuery's .on() to respond to clicks on the elements.
$('.pickup').on('click',
function(e) {
alert("hello");
}
);
Via some user interaction (in Google maps), I've got to add more elements to the div and want them to respond to clicks as well. For some reason they do not. I've pared it all down on jsfiddle:
http://jsfiddle.net/thunderrabbit/3GvPX/
When the page loads, note that clicking on the lines in output will alert('hello') via jQuery.
But click the [add] button and the new lines do not respond to clicks.
My HTML
<div id="unit_2225" class="pickup">
<span>Click me; I was here first</span>
</div>
<script type="text/template" id="unit-template">
<div class="unit-item">
<span class="pickup">
<span>click us (<%= unit_id %>) via underscore</span>
</span>
</div>
</script>
<div id="divID">
</div>
<button>add</button>
My Javascript
var addUnitToDiv = function(key,val) {
console.log(val);
var template = _.template($('#unit-template').html(),val);
$('#divID').append(template);
}
var unit_ids = [{unit_id:'hello'},
{unit_id:'click'},
{unit_id:'us'},
{unit_id:'too'},
{unit_id:112}];
$.each(unit_ids, addUnitToDiv);
var unit_pids = [{unit_id:'we'},
{unit_id:'wont'},
{unit_id:'respond'},
{unit_id:'to'},
{unit_id:'clicks'},
{unit_id:358}];
createMore = function() {
$.each(unit_pids, addUnitToDiv);
}
$('.pickup').on('click','span',function() {
alert("hello");
});
$('button').click(createMore);
I found a similarly worded question but couldn't figure out how to apply its answer here.
Instead of binding events directly to the elements, bind one event to their container element, and delegate it:
$("#divID").on("click", ".pickup", function () {
// Your event handler code
});
DEMO: http://jsfiddle.net/3GvPX/3/
In this case, the event handler is only executed for elements inside of the container #divID that have the class "pickup".
And in your scenario, the elements are being added to the element with an id of "divID". Thus, where the two selectors came from.
This is handy because, as you've found out, dynamically adding elements doesn't magically bind event handlers; event handlers bound normally with .on() are only executed (bound) on those present at the time of binding.
It could even help if you change the delegated selector to "span.pickup" (if you know the elements will always be a <span> like in your template), so that the DOM is filtered by the tag name first.
Reference:
http://api.jquery.com/on/#direct-and-delegated-events
Working demo http://jsfiddle.net/u2KjJ/
http://api.jquery.com/on/
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. You can attach the handler on the document level.
Hope it fits the need, :)
code try the code changed below
$(document).on('click','.pickup',function() {
alert("hello");
});
After initialize js I create new <div> element with close class and on("click") function doesn't work.
$(document).on('click', '.post-close', function () {
alert("hello");
});
but on('hover') work perfectly.
$(document).on('hover', '.post-close', function () {
alert("hello");
});
but I need to make it work on click.
It's because you're not preventing the default behaviour of the browser. Pass e into your handler and then use e.preventDefault()
$(document).on('click', '.post-close', function (e) {
e.preventDefault();
alert("hello");
});
Edit
Also, bind the handler before creating the new <div>
why not use something like
$('.post-close').click(function(){
//do something
});
If the element was added dynamically use:
$(document).on('click', '.post-close', function(){
//do something
});
edit:
like danWellman said, you can add the preventDefault IF you want to make sure no other code is executed. otherwise use the code above.
edit2:
changed the .live to .on
It's an old post but I've had a exactly same problem (element created dynamically, hover works, but click doesn't) and found solution.
I hope this post helps someone.
In my case, I found ui-selectable is used for parent element and that was preventing from click event propagate to the document.
So I added a selector of the button element to ui-selectable's 'cancel' option and problem solved.
If you have a similar probrem, check this
Try turn of libraries for parent element
You're not using stopPropagation() in parent element ?
i am modifying the inner html through javascript, and the inner html involves a button
but when i put in the jquery code to run on the button click event it fails to do so ..
sorry but im a newb when it comes to javascript
content im adding into the html ..
function add()
{
var val=document.getElementById("ans").value;
document.getElementById("answers").innerHTML+="<tr><td>"+val+"<br/><p align=\"right\"><button class=\"replyb\">replies</button></p>"+"</td></tr>";
document.getElementById("ans").value="";
}
jquery code ...
enter code here
At a guess, because we don't have your jQuery, I would say you need to use .live() instead of .click() when you change the HTML the button will be NEW to the DOM.
When you apply your jQuery code, it adds any calls like .click() to any DOM item, when the page loads. So any NEW element doesn't have a .click() handler added to them.
Do solve this, you can change your .click():
$('#someitem').click(function() {
.....
});
To something like this:
$('#someitem').live('click', function() {
.....
}
Add the following in your page at some place and it will handle clicks to all .replyb buttons whether you add them with javascript at any time, or not.
$(function(){
$('button.replyb').live('click', function(){
alert('clicked on button');
});
});
have a look at jquery .live() method