Check event target when using document.attachEvent - javascript

I have the following code...
document.attachEvent("onclick", get_func(obj, "on_body_click", "event_target_here"));
I am attaching a global function get_func() to the event onclick. get_func() returns reference to a function defined in a function object something like this..
function get_func(obj, funcname, params) {
if(funcname == "check") {
return obj.checkTarget(params);
}
}
Now in the function checkTarget(), I need to check which DOM object was clicked upon. How can I do this? I understand that I need to send the target of onclick event to the global function somehow.
Can somebody throw some light on this?
Regards

If you want to pass the object that was clicked on into the global function, you can modify your event attachment to use the click event's source element to something like this:
document.attachEvent("onclick", function(e) { get_func((e || event).srcElement, "on_body_click", "event_target_here") });
Then you could pass that object down to the checkTarget function.

Related

How to access $(this) and event in defined callback function

I'm trying to enable some touch controls through a callback function but I'm having trouble accessing the event as well as $(this) in my callback function. Right now the code looks as follows:
$('.img-responsive').each(touchControls);
function touchControls(event) {
event.preventDefault();
var mc = new Hammer(this);
mc.on("doubletap", function() {
console.log($(this));
});
}
Where '.img-responsive' is a class of images on my page.
When it tries to call event.preventDefault, I get an error that event.preventDefault is not a function. I thought the event was automatically passed to the variable called? I know when I did a named callback function with .on, event.preventDefault() worked perfectly fine. I assume it's different when I do it with .each, how do I properly access it?
Now, if I remove the event.preventDefault() line, when it logs $(this), I get a function. I was expecting to get individual elements so I could set touch controls for them, but that clearly didn't work. I tried to bind 'this' by:
$('.img-responsive').each(touchControls).bind(this);
But when I logged $(this), it was still a function and not the element I was expecting.
I'm basically just confused as to how to access $(this) and event within the defined callback function.
.each is not an event handler so its callback function does not accept an event object. The method signature of the each callback function looks like this:
.each( function )
function
Type: Function( Integer index, Element element )
A function to execute for each matched element.
So you won't have an event object to reference but, more importantly, there will be no default event behavior to prevent.
Conversely, on does in fact setup event handlers. Its callback function does take an event as its parameter. You can handle your event management within your event handler code, inside the callback function for .on.
this will refer to your current element as you iterate. But inside your inner callback function there will be a different context (so a different this). Simply store a reference to the element in the outer scope:
function touchControls() {
var $this = $(this);
var mc = new Hammer(this);
mc.on("doubletap", function(e) {
e.preventDefault();
console.log($this);
});
}
You have the event being passed in the wrong function.. You need to pass it into the event listener. The first argument of an each loop is the current index of the iteration.
$('.img-responsive').each(touchControls);
function touchControls(eachIndex) {
var mc = new Hammer(this);
mc.on("doubletap", function(event) {
// move preventDefault here and pass the event
event.preventDefault();
console.log($(this));
});
}
function Hammer(el){
return $(el)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="img-responsive">img</div>
<div class="img-responsive">img</div>

custom callback on jquery event

I am working with jquery and jstree
I have an event that triggers every time my tree changes:
$tree.jstree()
.on("changed.jstree", function(event, target) {
//manipulate data
});
It works perfect. I can access "this" (the tree), and also event and target. But, I am trying to define a custom callback. I tried something like this:
window.customCallback = (function(event, target) {
//manipulate data
//$(this).foo() manipulates the tree
//event.type to access the event type
//target.node to access the node
}(this));
So I can use:
$tree.jstree()
.on("changed.jstree", customCallback(event, target));
But it doesn't work. Could somebody help me out?
$tree.jstree().on("changed.jstree", customCallback(event, target));
What you're doing is setting the result of customCallback as callback handler.
What you want to do is set the function itself as callback handler:
var customCallback = function(event, target) {
// ...
};
$tree.jstree().on("changed.jstree", customCallback);
Notice the "missing" brackets - because brackets would invoke the function and we don't want that.
The parameters will be passed to the handler automatically.

The correct way to bind this?

I'm trying to access 'this' inside a method that is called from a button press, where this refers to both the class and the button pressed:
p.myVar = 'banana';
$('.go').on('click', this._init);
p._init = function(e){
//get the button pressed
//get this.myVar
};
To do this I bind this:
$('.go').on('click', this._init.bind(this));
The above works and I can now access my var via:
this.myVar; //banana
But I can no longer access the button.
How can I access it, use e.currentTarget or is there a better way?
You should use the data argument :
$('.go').on('click', {myVar:'banana'}, this._init);
p._init = function(e){
// use e.data.myVar;
// this is the right matching clicked element
};
I presume your declaring the event listener in a closure, if so you can use a local variable and pass it that, the reference is unique to the closure and can be accessed by the function in the listener when it is called. It becomes a kind of invisible global, the reference only exists to that specific call and the listener function but is still shared.
function initButtons(){
var selfRef = this;
$('.go').on('click',selfRef._init);
}

How to pass Event (e) and variables with event listeners?

I have an event listener like this:
div.addEventListener('mouseover',function(){bubble_info.call(data);},false);
function bubble_info(e,info){
//get e.pageX etc
//do stuff with info
}
This problem is in bubble_info the variable e holds the info of data and info is undefined
How do i make sure i can get e and info correctly?
Event Object has many useful properties and methods.
div.addEventListener('mouseover',function(event){
bubble_info(event, info);
// you can pass additional params that can be used in your handler
},false);
function bubble_info(event, info){
// you can access type of event from event object's properties
console.log(event.type);
console.log(info); // your additional parameter.
};
addEventListener Documentation
Use call only if you need to pass reference of this (current) object.
It's syntax will be ...
FunctionName.call(thisArg, arguments-list, ...);
call Documentation
Try this (you don't need the call unless you're passing a specific this reference - which you're missing in your code anyway):
div.addEventListener(
'mouseover',
function(event) {
bubble_info( event, dataYouWant );
},
false
}
For reference, a .call() should look like this: bubble_info.call( this, event, etc )

How can I create functions in jQuery and call it on event and pass variable to it?

$(".addcart").click(function(){
$("input[name='items']:checked").each(function() {
//doing something
});
});
I'm trying to create a common class onclick of which I'm doing something. Is there a way I can make "items" a variable, I mean Can I pass checkbox name to this event.
Try this and see if it works out:
$("input[name='items']:checked").each(function() {
alert(this.attr("name"));
});
I think I've used like this somewhere.
[EDIT]
The thing with this is that jQuery passes the current item to the foreach as the context of the variable.
Use bind instead of click
$(".addcart").bind("click", {name: "items"}, function(event){
$("input[name='" + event.data.name + "']:checked").each(function() {
//doing something
});
});
edit:
"How can I create functions in jQuery
and call it on event and pass variable
to it"
That will still be the same procedure. Use bind to attach an event handler, pass it an object with the needed stuff for your function. In your event handler call your function and pass it the object from event.data
$(".addcart").bind("click", {foo: "hello world"}, function(event) {
DoSomethingOnClick(event.data);
});
function DoSomethingOnClick(obj) {
obj = obj || {};
if (obj.hasOwnProperty('foo'))
alert(obj["foo"]);
else
alert("no foo here");
}
You know that all checked items will have a name of items, so that's not very interesting, but maybe you want to retrieve the value of each of the items:
$(".addcart").click(function(){
$("input[name='items']:checked").each(function() {
// To access an attribute of this item use the form $(this).attr(...)
alert( this.value );
});
});
The above uses this to access the element being iterated over. Take a look at the properties of a DOM element to see what properties of this you can access.
You can create a jQuery object out of this using the form $(this) then you can use .attr() to access the attributes of this. For example to get the class/es of this you can use either this.className or $(this).attr("class").
It is faster to directly access the DOM element's properties. But for some more complex manipulations it is good to know that $(this) is also available.

Categories

Resources