I have a page with a lot of e.stopPropagation so what I decided I would do was to create a function. here is code
function stopProp(name) {
if($(e.target).hasClass(name)) {
e.stopPropagation();
}
}
Though each time in console it does not seem to work at all and says stopProp is undefined.
Here is the actual JS I am trying to turn into a function
$('#chatting').on('click','.chatheader',function(e){
if($(e.target).hasClass('setting')) {
e.stopPropagation();
}
}
});
Anyone can help me to figure out why this is not working and how I should go about this? I figured it would be fairly easy just to change to a function so I can easily write stopProp('setting');though that is not the case here.
The handler of the click event should return with one single argument which will be the event. So you should have a function that returns an event, for example like this :
$('#chatting').on('click','.chatheader',stopProp('setting'));
function stopProp(name) {
return function(e) {
if($(e.target).hasClass(name)) {
e.stopPropagation();
}
}
}
You need to pass the event object to the stopProp method.
function stopProp(e) {
if($(e.target).hasClass(e.data.className)) {
e.stopPropagation();
}
}
Then
$('#chatting').on('click', '.chatheader', {className: 'setting'}, stopProp);
Demo: Fiddle
Related
I want the events click and touchstart to trigger a function.
Of course this is simple with JQuery. $('#id').on('click touchstart', function{...});
But then once that event is triggered, I want that same handler to do something else when the events are triggered,
and then later, I want to go back to the original handling function.
It seems like there must be a cleaner way to do this than using $('#id').off('click touchstart'); and then re-applying the handler.
How should I be doing this?
You can create a counter variable in some construct in your javascript code that allows you to decide how you want to handle your event.
$(function() {
var trackClicks = (function() {
var clicks = true;
var getClicks = function() {
return clicks;
};
var eventClick = function() {
clicks = !clicks;
};
return {
getClicks: getClicks,
eventClicks: eventClicks
}
})();
$('#id').on('click touchstart', function {
if (trackClicks.getClicks()) {
handler1();
} else {
handler2();
}
trackClicks.eventClick();
});
function handler1() { //firsthandler};
function handler2() { //secondhandler};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The way I would do this is by creating a couple of functions for the handler function to call based on certain flags. Sudo code would be something like this:
function beginning_action() {
...
}
function middle() {
...
}
var beginning_state = true;
$('#id').on('click touchstart', function{
if(beginning_state) {
beginning_action();
} else {
middle();
}
});
Then all you need to do is change the variable beginning_state to change which function is called. Of course you would give them better names that describe what they do and not when they do it.
Additionally, if you want the handler to call more than two functions you can change the beginning_state variable from a boolean to an int and check it's value to determine which function to call.
Good luck!
I just came to know about the jQuery .on() method and decided to use it as it was much cleaner than using multiple binds. It is working as long as I am using pre-defined events but when I am trying to add custom events it is not working.
I have this auxiliary function
var EV_ENTER_KEY = "enterKey";
function bind_events(cur_obj, e) {
if (e.keyCode == 13) {
$(cur_obj).trigger(EV_ENTER_KEY);
}
}
which I am using in the following code
CATEGORY_INPUT.on({
keyup: function (e) {
bind_events(this, e);
}
});
//Action for Category Search box Enter press
CATEGORY_INPUT.bind(EV_ENTER_KEY, function () {
alert("Aseem");
});
I am changing it to the following
CATEGORY_INPUT.on({
keyup: function (e) {
bind_events(this, e);
},
EV_ENTER_KEY: function () {
alert("Aseem");
}
});
But it is not working. No errors are being logged in console either for this. I looked and found this and I think I am using it correctly. The API reference did not have any examples of binding multiple events. Can someone tell whether I missed something in the API? If not what is the problem here?
It seems you have to give the custom event as string directly instead of storing it in a js variable and then using it.
If you change EV_ENTER_KEY to "enterKey" in your multiple event binding then it will work.
$(".myInput").on({
keyup: function (e) {
bind_events(this, e);
},
"enterKey": function () {
alert("Enter key pressed");
}
});
JS fiddle demo : http://jsfiddle.net/9ur4c/
It can be made to work like this. This is according to this answer
var EV_ENTER = "enter"
categoryInputEvents = {}
categoryInputEvents[EV_ENTER] = function(e) {
alert("Enter Event");
}
CATEGORY_INPUT.on(categoryInputEvents)
Although this still does not explain the thing reported by #Sanjeev but it is better to have alternatives.
I have a simple function that shows a div when the user clicks on a given checkbox. I'd like to have the same behaviour on another checkbox, so that's why I'd like to generalize it as a function passing the element to be shown.
But I'm not aware of the syntax on Jquery to do so. And it's triggering automatically when the page loads. Does anybody has an idea?
Code:
$(document).ready(function() {
$("#transcricao").change(
function(){
if ($('.form_transcr').css('display') === 'none') {
$('.form_transcr').fadeIn();
} else {
$('.form_transcr').fadeOut();
}
}
); //This is working fine!
$("#traducao").change( show_hide($('.form_trad')) );
//This is auto-trigerring without user action...
});
Here's my function:
function show_hide($elm){
//This is the "generalized" function that I'd like to use on both
//checkboxes, just passing the element.
if ($($elm).css('display') === 'none') {
$($elm).fadeIn();
} else {
$($elm).fadeOut();
}
}
Its auto-triggering without user action because you are invoking it.
Use
$("#traducao").change(function () {
show_hide($('.form_trad'));
});
As you are passing jQuery object so use it directly
function show_hide($elm) {
//This is the "generalized" function that I'd like to use on both
//checkboxes, just passing the element.
if ($elm.css('display') === 'none') {
$elm.fadeIn();
} else {
$elm.fadeOut();
}
}
The argument to .change() should be a function. You're not passing a function, you're calling the function.
$("#traducao").change(function() {
show_hide($('.form_trad'));
} );
BTW, your show_hide function seems to be equivalent to jQuery's fadeToggle method, so it can be:
$("#traducao").change(function() {
$(".form_trad").fadeToggle();
});
We have multiple animations against the same object. We need to take different actions when each of these animations end.
Right now, we bind to the webkitAnimationEnd event, and use a gnarly if/then statement to handle each animation differently.
Is there a way to essentially create custom webkitAnimationEnd events, allowing us to fire a specific event handler when a specific animation ends? For instance, fire handler1 when animation1 ends and fire handler2 when animation2 ends.
We're building for Webkit browsers, specifically Mobile Safari.
Thanks!
For a simple event-trigger, you can pass a function to jQuery's trigger() method and use the returned value of that function to call a trigger a specific event (which can then be listened-for:
function animEndTrigger(e) {
if (!e) {
return false;
}
else {
var animName = e.originalEvent.animationName;
return animName + 'FunctionTrigger';
}
}
$('body').on('bgAnimFunctionTrigger fontSizeFunctionTrigger', function(e){
console.log(e);
});
$('div').on('webkitAnimationEnd', function(e) {
$(this).trigger(animEndTrigger(e));
});
JS Fiddle demo.
You can, of course, also use the called function to either trigger the event itself or assess the passed parameters to determine whether or not to return an event at all:
One method to assess for a particular event to trigger is to use an object:
var animations = {
'bgAnim': 'aParticularEvent'
};
function animEndTrigger(e) {
if (!e) {
return false;
}
else {
var animName = e.originalEvent.animationName;
return animations[animName] ? animations[animName] : false;
}
}
$('body').on('aParticularEvent', function(e) {
console.log(e);
});
$('div').on('webkitAnimationEnd', function(e) {
$(this).trigger(animEndTrigger(e));
});
JS Fiddle demo.
Though, in this case, the return false should be altered so as not to provide the error Uncaught TypeError: Object false has no method 'indexOf' (which I've not bothered, as yet, to account for).
The following causes the called-function (animEndTrigger()) to directly trigger() the custom event (which requires an element on which to bind the trigger() method) and also avoids the Uncaught TypeError above:
var animations = {
'bgAnim': 'aParticularEvent'
};
function animEndTrigger(e, el) {
if (!e || !el) {
return false;
}
else {
var animName = e.originalEvent.animationName;
if (animations[animName]) {
$(el).trigger(animations[animName]);
}
}
}
$('body').on('aParticularEvent', function(e) {
console.log(e);
});
$('div').on('webkitAnimationEnd', function(e) {
animEndTrigger(e, this);
});
JS Fiddle demo.
Of course you're still, effectively, using an if to perform an assessment, so I can't be particularly sure that this is any tidier than your own already-implemented solution.
I wrote this in order to fix the problem IE has with select drop down lists being truncated if their options were longer than the default value of the select. Now it works fine but I want to improve the code in order to learn how to write things in a much more useable fashion.
$(document).ready(function() {
if ($.browser.msie) {
$('select').focus(function() { $(this).addClass('expand').removeClass('clicked'); })
$('select').blur(function() { $(this).removeClass('expand clicked'); })
$('select').mousedown(function () { $(this).addClass('expand').removeClass('clicked'); } )
$('select').hover(function () { }, function () {if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); $(this.blur()) }})
$('select').click (function() { $(this).toggleClass('clicked'); })
$('select').change(function(){ $(this).removeClass('expand clicked'); $('select.widerIE').blur() })
}
});
I tried making functions which were called by each event but that seemed to fail eg:
$('select').click(test (a))
function test (a) {
$(a).addClass('expand').removeClass('clicked')
}
It's not clear to me what you're trying to achive. One thing is sure - you can't define a event handler like that (see note below):
$('select').click(test (a))
Note: Technically, you could define your event handler like in code above. For that to work, function test would have to return a function that would be actual handler for the event.