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 ?
Related
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
I want to know how to check if my image was clicked using jquery...
Here is my html code
<img class="img-fade" src="img/message.png" id="messages" />
And my jquery code im using:
$('#messages').on("click", "img", function (e) { alert('hi'); }
But it still isnt working,
Could anyone help? Thanks :D
When you do:
$(selector1).on(event, selector2, function);
jQuery binds a handler to the event on the DOM elements that match selector1. When this handler runs, it walks the DOM hierarchy from the most specific element up to the element matching selector1, and checks whether any of the elements matches selector2. If it finds a match, it calls function with the appropriate execution context.
This is how on() is able to handle events on DOM elements that are added dynamically after the delegation is created.
i want to know how jquery' delegate or on(for delegate) works
In your case you made selector1 and selector2 the same element which caused trouble.
You can try this too
$('#messages').click(function(){
alert('hi');
}
$(function() {
$('#messages').on("click", function (e) {
$('.content2').fadeOut(3000);
window.setTimeout(function() {
window.location.href = 'messagecenter.html';
}, 3050);
});
});
I just fixed it :)
Instead of having $('#var').on("click", "img", function(e)) {});
I just removed the "img" part which I don't think was needed.
Thanks :)
i have this problem:
i am inserting certain html thru jquery. and in that inserted html i have a class to which i have binded a function. this function isnot beeing called, i have the feeling, the inserted html isnot seen yet by js.
my inserting code.
$(function(){
$('#einf').on('click', function(){
$('<tr><td><a class="ame">delete</a></td></td></tr>').insertAfter('#append_tr');
});
});
you can assume, inserting is working well. and this is my binded function:
$(function(){
$('.ame').on('click', function(){
alert('test');
});
});
i tested with already existing element with the same class ame, it is working with that. thanks for help and guidance
You have to run the click bind again on the added element.
Maybe something like this will work:
$('<tr><td><a class="ame">delete</a></td></td></tr>').insertAfter('#append_tr').find('.ame').on('click', function(){
alert('test');
});
Try with event delegation: http://jsfiddle.net/xehu9/
$('#einf').on('click', '.ame', function(e){ //<-----pass it here.
e.stopPropagation(); //<---------stop the event bubbling here.
alert('test');
});
This happens because you are trying to implement the click on a elem which is not present in the dom when page gets ready.
from the docs:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().
try .live() instead .on()
http://jsfiddle.net/ThobiasN/Pt3db/
$(function(){
$('#einf').on('click', function(){ alert ('some');
$('<tr><td><a class="ame">delete</a></td></td></tr>').insertAfter('#append_tr');
});
$('.ame').live('click', function(){
alert('test');
});
});
You cannot reference an element that was dinamically created, because it's not in the DOM when javascript runs, I suggest you use TEMPLATES instead of dinamic html content.
However, if you want to follow this approach, jquery allows concadinating element methods:
$(function(){
$('#einf').on('click', function(){
$('<tr><td><a class="ame">delete</a></td></td></tr>')
.insertAfter('#append_tr')
.on('click',function(){
alert('test');
});
});
});
lets say I have
function trigger(){
$('a.pep').each(function(){
$('a.pep').click(function(){
console.log($(this).val());
});
});
}
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
trigger(); //now i do but the others have duplicated trigger
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
});
So it seems that the click event is being applied twice/+ because the console.log is lauched more than once by click
How can i prevent this?
The problem is that you call $('a.pep').click() lots of times. (In fact, you bind as many click handlers as there are matching elements to each element. And then you do it again every time one of them is clicked.)
You should lever the DOM event bubbling model to handle this. jQuery helps you with the on method:
$(document.body).on('click', 'a.pep', function() {
console.log('element clicked');
$(document.body).append('<a class="pep">Click handlers handled automatically</a>');
});
See a working jsFiddle.
Note that I have removed the val call, because a elements can't have a value... Note also that the on method is introduced in jQuery 1.7; before that, use delegate:
$(document.body).delegate('a.pep', 'click', function() {
Small change to your trigger function is all you need. Just unbind the click event before binding to ensure that it is never added more than once. Also, you don't need to use each when binding events, it will add the event to each item automatically.
function trigger(){
$('a.pep').unbind('click').click(function() {
console.log($(this).val());
});
}
You can check using data('events') on any element if the required event is attached or not. For example to check if click event is attached or not try this.
if(!$('a.pep').data('events').click){
$('a.pep').click(function(){
console.log($(this).val());
});
}
you should use jQuery live here because you add DOM elements dynamicly and you want them to have the same click behaviour
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
$('a.pep').live('click', function(){
console.log($(this).val());
});
});
Try:
if($('a.pep').data('events').click) {
//do something
}
i think if you use live() event you dont need to make function
$('a.pep').live('click', function(){
console.log($(this).val());
});
I think I've been too much time looking at this function and just got stuck trying to figure out the nice clean way to do it.
It's a jQuery function that adds a click event to any div that has a click CSS class. When that div.click is clicked it redirects the user to the first link found in it.
function clickabledivs() {
$('.click').each(
function (intIndex) {
$(this).bind("click", function(){
window.location = $( "#"+$(this).attr('id')+" a:first-child" ).attr('href');
});
}
);
}
The code simply works although I'm pretty sure there is a fairly better way to accomplish it, specially the selector I am using: $( "#"+$(this).attr('id')+" a:first-child" ). Everything looks long and slow. Any ideas?
Please let me know if you need more details.
PS: I've found some really nice jQuery benchmarking reference from Project2k.de here:
http://blog.projekt2k.de/2010/01/benchmarking-jquery-1-4/
Depending on how many of these div.click elements you have, you may want to use event delegation to handle these clicks. This means using a single event handler for all divs that have the click class. Then, inside that event handler, your callback acts based on which div.click the event originated from. Like this:
$('#div-click-parent').click(function (event)
{
var $target = $(event.target); // the element that fired the original click event
if ($target.is('div.click'))
{
window.location.href = $target.find('a').attr('href');
}
});
Fewer event handlers means better scaling - more div.click elements won't slow down your event handling.
optimized delegation with jQuery 1.7+
$('#div-click-parent').on('click', 'div.click', function () {
window.location.href = $(this).find('a').attr('href');
});
Instead of binding all the clicks on load, why not bind them on click? Should be much more optimal.
$(document).ready(function() {
$('.click').click(function() {
window.location = $(this).children('a:first').attr('href');
return false;
});
});
I would probably do something like;
$('.click').click(function(e){
window.location.href = $(this).find('a').attr('href');
});