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>
Related
Problem:
I have some selects with options in my HTML code and I have set an on change event handler, to figure out, when a selection will be changed.
The following code shows the jQuery code to get the on change:
$(document).on('change', '.anyHtmlSelect', updateState);
I have an existing Javascript function, that should be used as callback function.
The Javascript function looks like:
function updateState(element)
{
var currentId = element.attr("id");
}
Question:
How can I get the changed select as element?
I have tried the following:
$(document).on('change', '.anyHtmlSelect', updateState($(this));
but it doesn't work.
The first argument that is automatically passed to an event handler is a reference to the event itself, not the element that caused the event. To access the DOM element that triggered the event, use this:
Simply change:
function updateState(element)
{
var currentId = element.attr("id");
}
to:
function updateState(event) {
var currentId = this.attr("id");
}
After some research I have found a solution I would share with you.
In my solution, I created an anonymous function, which calls the updateState function with $(this) as parameter.
$(document).on('change', '.anyHtmlSelect', function () {
updateState($(this));
});
Is there a better solution?
Callback method is not being called when I attach my event to element. The method in question belongs to an object but it seems the way I am calling it the method isn't being called when the click event occurs.
var myObject = {
handledrop : function () {
//retrieved created html element
var elem = document.getElementById("required");
elem.addEventListener("click", this.deleteFavorite.bind(this), false);
},
//this method isn't being called when click event occurs
deleteFavorite: function (evt) {
console.log(evt);
}
}
What am I doing wrong? How do I pass the right context so that the correct method is called and passed the right context which is event
Couple of debug/trouble-shooting tips:
Post the html for the "required" element.
Check that the "required" element you think you're getting is valid:
var elem = document.getElementById("required");
console.log('elem:',elem);
You can also iterate its properties to ensure that function exists:
foreach(var property in elem){
console.log('property:',property);
}
For cross browser support - you might want to read this post:
addEventListener vs onclick
I am trying to understand how is this code works
$("#imageGallery a").click(function(event){
event.preventDefault();
});
Why is the function handler (in this case "event") are executed? Isn't the handler supposed to be some var which isn't executed? feel free to share any keyword / article about this
Thankss..
The .click() method as you are using it takes an argument which is a callback function.
$("#imageGallery a").click(myCallback);
function myCallback(e) {
// the argument e which you can name anything you want is a
// jQuery event object
}
That callback function will be passed a single argument which is a jQuery event object. I've written the code above to use a separately defined function for the callback for illustration purposes. But, the function can also be defined inline as an inline anonymous function like this:
$("#imageGallery a").click(function(e) {
// the argument e is a jQuery event object
});
The jQuery event object has both properties and methods. .preventDefault() is one of the methods on that object. You can see a list of other properties on the object here in the jQuery doc.
event is not an event handler, it is an event object with properties and methods, including preventDefault() method that is being called in your example.
Your event handler is an anonymous function function(event){ event.preventDefault(); }
In this case, event (The first argument passed to your function) contains an object of the event that happened (In this case a click event). That event object creates functions such as preventDefault(), which tell the browser to ignore any future action from this event, such as opening the link that was clicked.
Try adding a line right before it:
$("#imageGallery a").click(function(event){
console.log(event);
event.preventDefault();
});
And take a look at your console (Press F12), and look as the console tab, and see what it outputs. You can see all the fields, and everything else that the event object contains.
To clarify things a bit more, event is not a handler, your entire function is:
function(event){
event.preventDefault();
}
jQuery will then pass the browser event object to this function when the event is fired, and your code will then execute.
I have this function executed in a script
$(document).ready(documentReady);
function documentReady(){
console.log("Ready");
$(".loadMore").on("click",loadMoreClicked(this.id));
}
function loadMoreClicked(elementID){
//do something with elementID
}
However, everytime the document loads up, it executes instantly the loadMoreClicked function - thus giving an error.
It seems that if I just want to assign a function to the click event without it being executed directly, I have to remove any argument.
Why does it happen, and how can I avoid it?
Just remove the parentheses and the argument, this will be available in the callback
$(".loadMore").on("click", loadMoreClicked);
function loadMoreClicked(){
var elementID = this.id;
}
You need to use an anonymous function to make the callback call
$(".loadMore").on("click",function(){ loadMoreClicked(this.id) });
Without this, the function is called immediately on document load causing the direct execution behavior you are observing. It will also assign the return value of the function (undefined in this case) to the click handler which is also undesirable.
$(document).ready(function(){
$('.loadMore').click(function(event) {
var self = $(this);
var element = self.attr('id');
});
});
Another option is to set an anonymous function as handler like this
function documentReady(){
console.log("Ready");
$(".loadMore").on("click",function(){
var element = this.id;
});
}
Its a good practice to delegate .off() before .on() to prevent multiple click event listener added to prevent memory leak. ie.
$(".loadMore").off("click").on("click",loadMoreClicked(this.id));
next, an event.preventDefault() would prevent any default action and intercepted by your function.
$(".loadMore").off("click").on("click", function(e) {
e.preventDefault();
loadMoreClicked(this.id);
});
Hope this helps.
function barvaInfo(event) {
$(document).ready(function(){
var nid = window.event.srcElement.id;
}
this works in IE but not in FF. Can i use jquery for this? i try with JQuery event api but then i do not know how to get ID from it.
If you're using jQuery, you'll need to assign a parameter to your event handlers, then pass the argument to your function on each event.
You may also want to call it from the context of the element that received the event.
// some mouseover event handler
$('div').mouseover( function( e ) {
barvaInfo.call( this, e )
});
function barvaInfo( event ) {
// element that originated the event
var nid = event.target.id;
// in this function, because we're using .call() to invoke it,
// "this" will reference the element that invoked the handler
}
The event object is normalized through jQuery for you and is passed into each event handler:
$('someelement').bind('click', function(event) {
var nid = this.id; // event.target.id
});
within the handler, this refers to the dom node of invocation. So this.id would address the id of the element. Alternative, the event object owns a property called target which also represent the element.
edit
As patrick dw pointed out, this will always be a reference to the node to which the event handler was bound to. event.target is exactly what it says, the element which is the actual target. See comments for an example link.