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 :)
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
So I'm currently using .append() to add a feature to all of the posts on a webpage, but when additional posts are loaded on the page, the appended features aren't included in the new content — I'm trying to come up with a way to make sure all of the new content has the appended feature too.
$(this).append('<div id="new_feature></div>');
Something like this?
$(this).live().append('<div id="new_feature></div>');
Maybe there's a way to make it constantly appending in a loop perhaps?
There is DOMNodeInserted event:
$('button').click(function() {
$('#appendme').append($('<div class="inner">').text(Math.random()));
})
$('#appendme').on('DOMNodeInserted','.inner',function() {
console.log(this);
});
DEMO
update: this seems not works in IE, try propertychnage event handler also ($('#appendme').on('DOMNodeInserted,propertychange') but i not sure, have no IE to check this right now.
update2: Domnode* seems deprecated according to mdn, they tell to use MutationObserver object instead
update3: seems here is no very crossbrowser solution for MutationEvents, see this answer, so my suggestion would be use code above, if event supported and fallback to setTimeOut or livequery option.
update4:
If you depend only on .append() you can patch jQuery.fn.append() like this:
jQuery.fn.append=function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
$(elem).trigger('appended');
}
});
};
$('button').click(function() {
$('#appendme').append($('<div class="inner">').text(Math.random()));
})
$('#appendme').on('appended','.inner',function() {
console.log(this);
});
DEMO2
may be more correct is to spoof jQuery.fn.domManip like here
jQuery documentation:
Use of the .live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks.
You can use setTimeout() function that can check for new <div>s every n milliseconds.
$(function(){
setInterval("Check4NewDivs();",1000);
});
So say this is a div with class="comment newdiv", so when it appears on the page for the first time, it has the class newdiv that will let the function know it was just dynamically created.
function Check4NewDivs(){
$(".comment .newdiv").each(function(){
$(this).append('<div class="new_feature"></div>').removeClass("newdiv");
});
}
It's append not appened.
live is a deprecated event handler. It's not used this way. use on instead.
http://api.jquery.com/live/
So, the following code will run when you click selector.
$(document).on('click', 'selector', function() {
$(this).append('<div id="new_feature></div>');
});
No, there is no standard way to do it like that. There was a proposal of the events that would be fired whenever the DOM elements are inserted etc., but you cannot rely on that.
Instead rely on either:
(preferably) callbacks - just invoke function ensuring existence of such appended snippets, whenever you pull something (but after you successfully pull it from server and insert into DOM, not sooner), or
constant checks - like using in setInterval() or setTimeout(), but this would be unnecessary processing and you will never get instant append, unless you will perform processing-heavy checks all the time,
use the on load function:
$(item).on('load',function(){
$(this).append('<div id="new_feature"></div>');
});
This will add append the item as a callback once the item has been loaded. I would also choose some sort of dynamic ID creator rather than always append stuff with the same ID, but thats just me.
you must bind to an element that already exists on the page. i have written an example where i make appended content live.
DEMO on JSFiddle
HTML
<div id="container">
<div id="features">
</div>
<br />
<a href='#' id='clickme'>click me to add feature</a>
</div>
JS
$(function() {
$('#clickme').on('click', function(e) {
$('#features').append('<div class="new_feature">new feature</div>');
});
$('#features').on('click', '.new_feature', function() {
alert('i am live.');
});
});
I was under the impression that jquery's on() reacted to events attached elements dynamically added to the dom (via ajax or cloning, etc). However, the following is only working for the element attached to the dom at page load. The other copy I make of it using clone() is not being, well, handled.
$(document).ready(function () {
$('.ship_via_dropdown').on('change', function () {
console.log($(this));
if ($(this).hasClass('prev_change')) {
console.log('has');
} else {
$(this).addClass('prev_change');
console.log('hasn\'t');
}
});
});
Code for cloning:
$(document).ready(function(){
var form1 = $('.line_item_wrapper').children().clone();
$('#new_line_content_1').html(form1);
});
HTML for dropdown (contents added by jquery db query on document ready)
<span class="select ship_via_select_container">
<select class="ship_via_dropdown ship_via_dropdown_1">
</select>
</span>
Thank you for any insight!
Either delegate the event instead:
$(document).on('change', '.ship_via_dropdown', function () {
console.log($(this));
if ($(this).hasClass('prev_change')) {
console.log('has');
} else {
$(this).addClass('prev_change');
console.log('hasn\'t');
}
});
Or better yet, use .clone(true) to clone with events. (Note: this will only work if you're cloning AFTER the event handler is attached.)
It does, but not in the way that you think. When used as you have used it:
$('.ship_via_dropdown').on('change',
It is really not different than using .change(). What you are looking for is event delegation. This takes the following form:
$("<selector to static ancestor>").on('change', '.ship_via_dropdown', function () {
Where <selector to static ancestor> is a selector to a static ancestor of the dynamically added elements. (one that is not dynamically created) As a last resort document can be used here. However for performance, this should be the closest static ancestor element.
jquery's on() reacted to events attached elements dynamically added
No - or at least, only if you use it with delegated events. The live method did always delegate events to the document.
Change this line:
$('.ship_via_dropdown').on('change', function () {
to this:
$(document).on('change',".ship_via_dropdown", function () {
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 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');
});