As mentioned, I'm trying to bind clicking the 'a' tags on my page to my handleClickTag() function, but am struggling to implement the .on() method to bind the function and 'a' tag. I'm not sure if bind() would be more appropriate. Hope this makes sense!
a.data('tagId', tag.id); //save info inside html element
$(a).on('click', handleClickTag(a)); //bind click event of the "a" tag to the "handleClickTag" function - need help here
//code above contained inside forEach loop
function handleClickTag (event) {
var link = $(event.target);
var tagId = link.data('tagId');//would like to retrieve data from the tagId variable
//---continue function after data is correctly retrieved
}
To pass argument to the function you can wrap the function call inside of an anonymous function:
$(a).on('click', function(){ handleClickTag(a); });
Though I think you do not need to pass the argument here, Simply the following should work:
$(a).on('click', handleClickTag);
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?
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>
To initiate the onclick event, I have this
[].forEach.call(btnAddVendorDropDown, (btnAddVendorDropDown) => {
btnAddVendorDropDown.addEventListener('click', onAddVendorDropDownClick, false);
});
The function is
function onAddVendorDropDownClick(e) {
e.preventDefault();
addNewClass(modal, 'is-active');
addNewClass(modalAddVendorDropDown, 'is-active');
const test = $(this).attr('id');
console.log(test);
return test;
}
So what I'm trying to do is when a user clicks btnAddVendorDropDown, the function onAddVendorDropDownClick is called. I need to grab the id from the element. When I do console.log of the element attribute id from inside the function, I get exactly what I need. The problem I'm running into is when I try to grab it from outside the function, I keep getting undefined. I don't understand how I can grab the id once it calls this function from outside this function.
I tried this
var num = onAddVendorDropDownClick();
console.log("the function return is " + num);
Which is what shows undefined.
this is related directly to the caller's scope. This means that without "binding" a scope to your event handler, this is going to refer to your main application scope, and not the scope that jquery passes as you chain functions.
You can either wrap the event object's target:
function onClickHandler(e) {
$(e.target).attr('id');
}
Or you can use $(this) within the jquery context of a click handler:
$('#my-button').on('click', function(e) {
$(this).attr('id');
});
The last example works because it is occurring inside a JQuery closure, so it retains the scope from the previous function. Outside of a closure, this means something else.
$(this) is JQuery context, and you are inside javascript function. You can change the click button to JQuery to use it:
var test;
$("button").click(function(){
test = $(this).attr('id');
console.log(test);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btnTeste">
Teste
</button>
I have a global function defined in one place:
function addToCart (){
var prodText = $(this).parent().siblings(".item1").text();
$("#"+prodId+"shopC").children(".item1").text(prodText);
alert(prodText);
}
Then, I want to call it inside a HTML element with an inline onClick event:
onClick='addToCart()'
It is not working, but it works if I put the function code directly inside the onClick event, so that must be a this scope issue.
There are many questions/explanations about this scope but I must confess I miss a simple straight answer for this specific case (I tried to use "use strict" with success either).
How to make this work?
As per current implementation this doesn't refers to the element which invoked the function. It refers to window object.
You need to pass the current element context i.e. this to the function as
onClick='addToCart(this)'
and modify the function to accept element as parameter.
function addToCart (elem){
var prodText = $(elem).parent().siblings(".item1").text();
$("#"+prodId+"shopC").children(".item1").text(prodText);
alert(prodText);
}
Basically this inside a plain function will point to window. you have to pass the this context to the inline handler onClick='addToCart(this)'. Receive it and use it inside of event handler like below.
function addToCart (_this){
var prodText = $(_this).parent().siblings(".item1").text();
you have to pass this keyword where you inline calling the addToCart function then you can capture that element
onClick='addToCart(this)'
this object in your function does not point to the object where you added the onClick function to. It rather points to the window object.
You need to pass this as a param to your function.
function addToCart (trigger) { // Code goes here }
and call addToCart(this) in your onClick.
Learn more about this in javascript here.
I created a custom variable/function that I am trying to execute when an element is clicked. For some reason, it decides to display onload and ignores the .click(). I've spent a while now trying to figure this out, but I'm not having much luck.
Here's my custom function:
var movebox = function (entry) {
$imagebox.css('left' , '0');
$('#wr').append(entry);
};
I'm attempting to call it like this, but it calls it when the page loads instead.
$l3.click(movebox('test'));
You're calling the movebox function immediately instead of passing the function as a reference to the click event handler. This is a common mistake in JavaScript. Instead, pass in your function inside of an anonymous function, like so:
$l3.click(function() {
movebox('test');
});
As an aside, the same mistake is oftentimes made with setTimeout, setInterval, addEventListener, and the infamous eval. Remember, when treating functions as arguments to another function, be sure to wrap them in anonymous functions.
You are calling the movebox then passing the returned value to click event handler, in this case you can use the .on() event registration helper to pass a data element to the event handler which can be accessed using the event object.
Try
var movebox = function (e) {
$imagebox.css('left' , '0');
$('#wr').append(e.data.entry);
};
$l3.on('click',{ entry: 'test'}, movebox);