dynamically bind .on() method with event-map - javascript

I'm using this syntax to make sure that the events bind on dynamically added li elements
$('ul.list').on('click', 'li', function() {
//do something
});
I tried to archive the same with an event-map like this:
$('ul.list').hammer({
css_hacks : false
}).on({
swipe : function(event){
//do something
},
doubletap : function(event){
//some more code
}
}, 'li');
but its not working at all.
If I bind the events directly to the li element it works fine for existing elements, but not for dynamically added elements.
$('ul.list').find('li').hammer({
css_hacks : false
}).on({
swipe : function(event){
//do something
},
doubletap : function(event){
//some more code
}
});
How to bind the event-map to future elements?

on() with 2 parameters is eqvivalent to the old bind() functionality.
If you want to make it work like live() did, pass a third argument like in your first example.
Also, if your'e having trouble when chaining functions on the hammer() method, inspect it and make sure that it returns "this".
$('ul.list').on({
swipe : function() { ... },
doubletap : function() { ... }
},'li');

if you look into jquery document,jquery live
it says,Chaining methods is not supported. For example, $("a").find(".offsite, .external").live( ... ); is not valid and does not work as expected.
so you can do this:
$('ul.list > li').hammer({
css_hacks : false
}).live({
swipe : function(event){
//do something
},
doubletap : function(event){
//some more code
}
});
but it's deprecated, I think your first example should work.
I tried this:
<ul>
<li>aaa</li>
<li>bbb</li>
</ul>
and
$("ul").on({
click:function(){
$(this).html('clicked');
},
dblclick:function(){
$(this).html('double clicked');
}
},'li');
it works, so i guess your problem may be the name of event.

Related

Change hover state css with jQuery [duplicate]

This is what I have:
$('#blah').hover(function(){
$('etc').show();
}, function(){
$('etc').hide();
});
This works just fine, now I want the exact above code working live with on() method:
$('#blah').on('hover', function(){
$('#etc').show();
}, function(){
$('#etc').hide();
});
But this is not working, anybody knows why? but also this works:
$('#blah').on('hover', function(){
$('#etc').show();
});
When I'm using on() method, the callback function is not working, so I'm using mouseover() and mouseleave() with on() and it's working, I just wanted to know why hover callback is not working with on(), that's so simpler than using 2 events....
Thanks
from Jquery docs. Jquery on
Deprecated as of jQuery 1.8: The name "hover" used as a shorthand for
the string "mouseenter mouseleave". It attaches a single event handler
for those two events, and the handler must examine event.type to
determine whether the event is mouseenter or mouseleave. Do not
confuse the "hover" pseudo-event-name with the .hover() method, which
accepts one or two functions.
$("div.test").on({
mouseenter: function(){
$(this).addClass("inside");
},
mouseleave: function(){
$(this).removeClass("inside");
}
});
From the JQuery source code, hover is not included in the event list that triggered leading to JQuery .on()
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
It is because .hover() is just a shortcut for JQuery .mouseenter() and .mouseleave()
jQuery.fn.hover = function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
};
I hope this brief explanation provides little guidance.
Use mouseenter and mouseleave for hover. Check using hover with on here.
$("#blah").on(
{
mouseenter: function()
{
//stuff to do on mouseover
},
mouseleave: function()
{
//stuff to do on mouseleave
}
});
Use toggle to show / hide,
$('#blah').on('hover', function(){
$('#etc').toggle();
});
It's because hover is not really a browser event, in fact its just a shorthand for calling
$(selector).mouseenter(handlerIn).mouseleave(handlerOut);
Using with the .on('hover') form have been deprecated as of version 1.8.
use
jQuery.on("hover","#blah", function..)
Or you can use toggle feature of jQuery too
Yes it will not work because when you use .on() with hover then hover event just have one call-back function instead you can use multiple events in .on()
Try
$("DOM").on({
mouseenter: function() {
// Handle mouseenter...
},
mouseleave: function() {
// Handle mouseleave...
}
});
Use toggle()
$('#blah').on('hover', function(){
$('#etc').toggle();
});

How to toggle an element with on()?

I am using the Hammer.js library for mobile touch events and in their example for use with jQuery, they have the following:
$('#test_el').hammer().on("tap", ".nested_el", function(event) {
console.log(this, event);
});
This is straightforward; however, I would like to incorporate a toggle behavior to #test_el. In other words, if the above example was replaced with something like this:
$('button').hammer().on("tap", function() {
$('div').addClass('open');
}, function {
$('div').addClass('close');
});
How would I get this "toggle" behavior to work?
Initially, you could add a starting class to all buttons. Then on event, you can check if the class exists. This lets you know what state the element was in when you tapped it.
$('button').addClass('close');
$('button').hammer().on('tap', function() {
if ($(this).hasClass('close')) {
$(this).removeClass('close').addClass('open');
// Event code
}
else {
$(this).removeClass('open').addClass('close');
// Event code
}
});
jQuery also provides a toggleClass method.
There is already a toggleClass function available in JQuery, it seems that it does what you want.
Try:
$('#test_el').hammer().on("tap", ".nested_el", function(event) {
$(this).toggleClass("classnamehere");
});
Where classnamehere would be your class name.

jquery add listener to appended content

I have some jQuery code like this:
$("#add").click(function(event){
$("#list").append('<a class="remove" href="#">x</a>');
return false;
});
$('.remove').live('click', function(){
alert("123");
});
If one clicked on class=remove I would like it to alert 123. This doesn't happen though. I think this is a simple idea but I must be missing something.
Any ideas?
Thanks.
Live is deprecated, use on
$(document).on('click','.remove',function(){
alert("123");
});
Another way to add element and bind event without delegation:
$("#add").click(function(event){
$("<a />", {
"class": "remove",
href: "#",
text: "x"
}).on("click", function() {
alert("123");
return false;
}).appendTo("#list");
return false;
});
Avoid using live method, since it was deprecated and finally removed in the last version of jQuery.
try on delegate function..since you are apending that to list... you can use #list which is better in performance that the document
$('#list').on('click','.remove', function(){
alert("123");
});
you can go through the link to read more about on() event

Automatically assign event handler to new element

Say I have some code like this which is called on $(document).ready()
$(".someClass").click(function(){
//do something
});
Later on I have some jquery to create an element with the class someClass. Is there anyway to automatically attach the click from above or do I have to manually attach it again?
Yes. It is possible.
$("body").on("click", ".someClass", function() {
// ...
});
Use latest version of jquery and on
$(document).on('click', '.someClass', function(e){
//do something
});
Live is deprecated but you can use it, anyway (not recommended).
$('.someClass').live('click', function(e){
//do something
});
There is live, which also listens for new elements
$(".someClass").live('click', function(){
//do something
});
But, as of jquery 1.7 it has been deprecated. It's advised to use on instead.
But in order to use on, you need a container for the elements you want to bind a handler. Of course you could use body or document but it's better to use a more specific element
$(".someClassContainer").on('click', '.someClass' function(){
//do something
});
There's two easy ways of doing this, the first is with on():
$(".someClassParentElementPresentInTheDOMonDOMReady").on('click','.someClass',
function(){
//do something
});
And the other is to simply assign the click-handler at the point of creation of the new element; I don't know how you're doing that, but an example is below:
$('#addElement').click(
function(){
var newElem = $('<div />',{'class' : 'someClass'}).click(function(){
// do something }).appendTo('.someClassParentElementPresentInTheDOMonDOMReady');
References:
on().

After jQuery ajax load or update, I lose the mouseover event

After using .load to update my div, that is add item to my list, I used firebug and saw that the list was updated. However, I lost the mouseover event that worked when the page first loaded. In my script js I have:
// hide and show are css classes that display none and block respectively
function openList(){
$("#miniList").removeClass().addClass("show");
}
function closeList(){
$("#miniList").removeClass().addClass("hide");
}
...
$(document).ready(function() {
$("#miniList").mouseover(function() {
openList();
})
$("#miniList").mouseout(function() {
closeList();
})
});
function addItemToDiv(id, ref, num) {
$("#miniList").load("/list/ajax_updateList.jsp", {
'action' : 'additem',
'pid' : id,
'pref' : ref,
'qty' : num
});
}
Of course, this works fine the first time the page is loaded, but when I add item to the list, DOM is update but mouseover effects don't work any more.
Any thoughts are more than welcomed.
For DOM elments added dynimically you need to use the jquery .live() function.
Please go through the below link, I think that might fix your problem:
api.jquery.com/live
#ishwebdev, this is common problem we run , for all the DOM elments added after pageload like run time, we need to bind the events through live instead of regular bind
If you are using jquery 1.4 use below code:
// from jquery.com
$('give your selector here').live('mouseover mouseout', function(event) {
if (event.type == 'mouseover') {
// do something on mouseover
} else {
// do something on mouseout
}
});
#siri: thanks for the excellent answer, it worked for me right away. Here's my shopping cart dropdown example:
Before:
$("#cart-items").mouseenter(function(){
$('#cart-pulldown').show();
});
After:
$("#cart-items").live('mouseenter', function(){
$('#cart-pulldown').show();
});
With .live the event handling still works even after I change the underlying HTML via an Ajax call.
The selected answer no longer works for jquery 1.9+.
Instead, use "on" event, like
$( document ).on("keyup", "input.assets",function(event) {...
http://api.jquery.com/on/

Categories