JQuery .on() method with multiple event handlers to one selector - javascript

Trying to figure out how to use the Jquery .on() method with a specific selector that has multiple events associated with it. I was previously using the .live() method, but not quite sure how to accomplish the same feat with .on(). Please see my code below:
$("table.planning_grid td").live({
mouseenter:function(){
$(this).parent("tr").find("a.delete").show();
},
mouseleave:function(){
$(this).parent("tr").find("a.delete").hide();
},
click:function(){
//do something else.
}
});
I know I can assign the multiple events by calling:
$("table.planning_grid td").on({
mouseenter:function(){ //see above
},
mouseleave:function(){ //see above
}
click:function(){ //etc
}
});
But I believe the proper use of .on() would be like so:
$("table.planning_grid").on('mouseenter','td',function(){});
Is there a way to accomplish this? Or what is the best practice here? I tried the code below, but no dice.
$("table.planning_grid").on('td',{
mouseenter: function(){ /* event1 */ },
mouseleave: function(){ /* event2 */ },
click: function(){ /* event3 */ }
});

That's the other way around. You should write:
$("table.planning_grid").on({
mouseenter: function() {
// Handle mouseenter...
},
mouseleave: function() {
// Handle mouseleave...
},
click: function() {
// Handle click...
}
}, "td");

Also, if you had multiple event handlers attached to the same selector executing the same function, you could use
$('table.planning_grid').on('mouseenter mouseleave', function() {
//JS Code
});

If you want to use the same function on different events the following code block can be used
$('input').on('keyup blur focus', function () {
//function block
})

I learned something really useful and fundamental from here.
chaining functions is very usefull in this case which works on most jQuery Functions including on function output too.
It works because output of most jQuery functions are the input objects sets so you can use them right away and make it shorter and smarter
function showPhotos() {
$(this).find("span").slideToggle();
}
$(".photos")
.on("mouseenter", "li", showPhotos)
.on("mouseleave", "li", showPhotos);

And you can combine same events/functions in this way:
$("table.planning_grid").on({
mouseenter: function() {
// Handle mouseenter...
},
mouseleave: function() {
// Handle mouseleave...
},
'click blur paste' : function() {
// Handle click...
}
}, "input");

Try with the following code:
$("textarea[id^='options_'],input[id^='options_']").on('keyup onmouseout keydown keypress blur change',
function() {
}
);

Related

Jquery not binding event onload

(function() {
var bgOn;
$(".ContainingBox").on('hover', function() {
function() {
bgOn = $(this).css("background-color");
$(this).css("background-color", "#e5fff8");
}, function() {
$(this).css("background-color", bgOn);
}
});
})();
I want to bind an event for hover. This code worked fine when I did not wrap it in the anonymous function, and used .hover() . However, we have a requirement to not use global variables. So i need to bind the event!
Is this not possible?
Your code has syntax errors, specifically on() does not accept multiple callbacks etc.
Also, there is no native hover event, you should use mouseenter and mouseleave instead
$(".ContainingBox").on({
mouseenter: function() {
$(this).data('bg', $(this).css("background-color"));
$(this).css("background-color", "#e5fff8");
},
mouseleave: function() {
$(this).css("background-color", $(this).data('bg'));
}
});
Using jQuery's data(), and not a single variable, will remember the background color for each element
FIDDLE
try this....
(function() {
var bgOn;
$(".ContainingBox").on('mouseover', function() {
function() {
bgOn = $(this).css("background-color");
$(this).css("background-color", "#e5fff8");
}, function() {
$(this).css("background-color", bgOn);
}
});
})();

jQuery hover event is not recognized

The below code works -
$("#x").hover(function() {
alert("hovered");
});
But the below code does not. Please explain why?
$("#x").on("hover", function() {
alert("hovered");
});
Note - #x is a button element. and the above code works for "click" event
From jQuery .on()'s documentation:
Deprecated in jQuery 1.8, removed in 1.9: 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.
You could pass an object to the on method:
$("#x").on({
mouseenter: function() {
// ...
},
mouseleave: function() {
// ...
}
});
And if you want to delegate the events:
$('#aStaticParentOfX').on({
mouseenter: function() {
// ...
},
mouseleave: function() {
// ...
}
}, "#x");
Even the .live() has depricated from jQuery 1.9 if your version is below 1.9 you can use
$("#x").live("hover", function() {
alert("hovered");
});
First: jQuery hover need 2 functions as arguments More here: http://api.jquery.com/hover/
$('#x').hover(
function() {
// your 'mouseenter' event handle
}, function() {
// your 'mouseleave' event handle
});
Second: you can simply use CSS hover pseudo-class if your code operate on the same element (#x)
#x:hover {
// this will be added to #x when 'mouseenter', and remove when 'mouseleave'
background-color: red;
}
try this..
$("#x").on("mouseover", function () {
//wrire your code here
});
if you populated elements through javascript,use the following. It is replacement for deprecated jQuery.live.
$("body").on("mouseover","#x", function () {
//wrire your code here
});
see this js fiddle http://jsfiddle.net/3aq48p5m/3/

Show/Hide after a div created dynamically

I use this code to show/display Edit link when mouse hovers over the start div. This div however can be created dynamically and when it's created the code below doesn't work.
$(".start").hover(
function() {
timeclock.utils.displayEdit(this)
},
function() {
timeclock.utils.hideEdit(this)
});
I tried the code below but it doesn't work and it looks wrong. How can I implement $(document).on('hover'.....) to hide/show the Edit link as shown above?
$(document).on("hover", ".start",
function() {
timeclock.utils.displayEdit(this)
},
function() {
timeclock.utils.hideEdit(this)
});
hover() is a shortcut for binding mouseenter and mouseout handlers. Your second example doesn't work because on() doesn't take two functions like that. You bind multiple handlers at once using delegated events like this:
$(document).on({
mouseenter: function () {
timeclock.utils.displayEdit(this);
},
mouseleave: function () {
timeclock.utils.hideEdit(this);
}
}, '.start');
Simple example: http://jsfiddle.net/TRcR9/
There are 2 errors in your code.
1. you should use $(this) instead of this. There is a different between this two.
2. you have to bind the hover again whenever a new div is created.
Your syntax is a little off. You can attach multiple event handlers simultaneously using a plain object.
$(document).on({
mouseenter: function(){
timeclock.utils.displayEdit(this);
},
mouseleave: function(){
timeclock.utils.hideEdit(this);
}
}, ".start");
I've created a Codepen example here: http://cdpn.io/dDewi
The syntax you have is a a little off. Here is a jsfiddle with a working example:
HTML:
<div id="container"></div>
CSS:
#edit { display: none; }
Javascript:
$(function() {
$(document).on(
{
mouseenter: function()
{
$('#edit').show();
},
mouseleave: function()
{
$('#edit').hide();
}
},
'.start'
);
$('#container').prepend('<div class="start">Mouse over me <a id="edit" href="#">edit</a></div>');
});

Is it possible to bind multiple functions to multiple delegation targets in one place?

As it is possible to define multiple event handlers in one single function in jQuery like this:
$(document).on({
'event1': function() {
//do stuff on event1
},
'event2': function() {
//do stuff on event2
},
'event3': function() {
//do stuff on event3
},
//...
});
Then again we can do this:
$(document).on('click', '.clickedElement', function() {
//do stuff when $('.clickedElement') is clicked
});
I was wondering if it is also possible to do something like this (the following code does not work, it's just for illustration):
$(document).on('click', {
'.clickedElement1', function() {
//do stuff when $('.clickedElement1') is clicked
},
'.clickedElement2', function() {
//do stuff when $('.clickedElement2') is clicked
},
//... and so on
});
This code gives me an error complaining about the "," after '.clickedElementX'. I also tried it like this:
$(document).on('click', {
'.clickedElement1': function() {
//do stuff when $('.clickedElement1') is clicked
},
//... and so on
});
Then I don't have the error but also the function is not executed. Is there a way to collect all the click handlers in one place like this or would I have to always do it like this:
$(document).on('click', '.clickedElement1', function() {
//do stuff when $('.clickedElement1') is clicked
});
$(document).on('click', '.clickedElement2', function() {
//do stuff when $('.clickedElement2') is clicked
});
//... and so on
You can chain :
$(document).on({
click: function() {
//click on #test1
},
blur: function() {
//blur for #test1
}
}, '#test1').on({
click: function() {
//click for #test2
}
}, '#test2');
FIDDLE
Short answer: no, you have to bind them all separately.
Long answer: You can create an "infrastructure" for your site and have all events in one place. e.g.
var App = function(){
// business logic
return {
Settings: { ... },
Events: {
'event1': function(){
},
'event2': function(){
},
'event3': function(){
}
}
}
}();
Then wiring it up involves:
$(document).on(App.Events);
Then internally you can add then new bindings to your App object but still remains wired up in only one place (as far as jQuery is concerned). You could then make some kind of subscriber model within App (e.g. App.Subscribe('click', function(){ ... })) and each new subscription still is only wired through the single .on() binding.
but, IMHO, this is a lot of overhead with very little pay-off.
$(document).on('click' , function(e){
if($(e.target).hasClass("some-class")){
//do stuff when .some-class is clicked
}
if($(e.target).hasClass("some-other-class")){
//do stuff when .some-other-class is clicked
}
});
you can choose any some-class you want
It can be easily done, really:
$(document).ready(function()
{
$(this).on('click', '.one, .two',function()
{
if ($(this).hasClass('one'))
{//code for handler on .one selector
console.log('one');
}
else
{//code for handler on .two selector
console.log('two');
}
console.log(this);//code for both
});
});
If multiple events is what you're after:
$(document).ready(function()
{
$(this).on('click focus', '.one, .two',function()
{
if (event.which === 'click')
{
if ($(this).hasClass('one'))
{
console.log('one');
}
else
{
console.log('two');
}
}
else
{
console.log('focus event fired');
}
console.log(this);
});
});
Play around with this: here's a fiddle
documentation on event
jQuery's on, which is used here as though it were delegate
you can use a helper function:
function oneplace(all){
for (var query in all){
$(query).on('click', all[query]);
}
}
and then call:
oneplace(
{'#ele1':function(){
alert('first function');
},
'#ele2':function(){
alert('second function');
}});
jsfiddle here: http://jsfiddle.net/5zwkf/

How to give two functions to delegate function

I'm using JQuery and trying to use delegate for the hover action. Problem is the hover action can get two handlers, the handle in and the handle out. How can I achieve this using delegate?
I've tried this and it didn't work:
$(document).delegate('.box', 'hover',
function() { $(".a").addClass(".hover");},
function() { $(".a").removeClass(".hover");});
According to the docs for .hover:
$(selector).mouseenter(handlerIn).mouseleave(handlerOut);
So you should be able to just call delegate once for each of these functions:
$(document)
.delegate('.box', 'mouseenter', function() { alert(1); })
.delegate('.box', 'mouseleave', function() { alert(2); });
An alternative to #Justin's solution is to check the event type in the callback:
function onMouseenter()
{
alert(1);
}
function onMouseleave()
{
alert(2);
}
$(document).delegate('.box', 'hover', function(event)
{
if (event.type === 'mouseenter') onMouseenter.apply(this, arguments);
else onMouseleave.apply(this, arguments);
});
That said, it's unnecessary to use .delegate() if you're just going to delegate to document. Use .live() instead, which is much more concise:
$('.box').live('hover', function (event)
{
// snip...
});

Categories

Resources