jQuery : "this" property is not working on $(document) click - javascript

I want to change my clicked image src. I tried it using this. The reason is I am using $(document) for click function. The code I am using is shown below. It will change without using this property. But I need to work it using this property.
$document.on('click', 'img.flagImg', function () {
_flag();
})
var _flag = (function(){
$(this).attr('src',"images/flag.jpg")
})
but its not getting. can any one suggest another option for getting a good solution.

When you call a function like that, _flag(), this is set to the global object (in loose mode) or undefined (in strict mode).
Just let jQuery set this for you:
$document.on('click', 'img.flagImg', _flag);
But if you want to avoid jQuery passing it the event argument, you can use call to set this explicitly instead:
$document.on('click', 'img.flagImg', function() {
_flag.call(this);
});

Related

jQuery which is the correct function definitions?

I saw three different function definitions in jQuery. What is the correct way to use them?
Example 1:
function example() {
// code here
}
Example 2:
jQuery('#Example').click(function() {
// code here
});
Example 3:
var example = {
demo : function() {
// code here
}
}
Why should I choose which?
There is no 'best' here, as each function definition is separate and serves different purposes. Also note that only the second example has anything to do with jQuery.
Your first example is just a vanilla JS function definition, nothing special about this.
Your second is a jQuery click event handler which is used to declare logic which should be executed when the click event occurs on the selected element.
The third example is a function definition inside an object, which can be useful when using an OOP approach (as if to declare a class/model), or just passing a collection of values around in your logic.
Example 1 and 3 have nothing to do with jQuery. These are vanilla javascript snippets.
On example 2, it's recommended to use this syntax instead :
jQuery('#example_container').on('click', '#Example', function(event) {
// code here
});
This lets you delegate the event handling, which means even if you created that element after the page was loaded, the event will still be handled.
Your first example:
function example() {
// code here
}
Is the way to define a function and it is going to be available depending on its scope.
The second example:
jQuery('#Example').click(function() {
// code here
});
You are not only defining a Function but you are adding this function into the click event for a html element that has the id "Example"
The third Example:
var example = {
demo : function() {
// code here
}
}
You are defining a function inside an Object. So this function is going to be the method "demo" of the object "example" you just created.

Passing an attribute's value of the clicked element to an external function through jquery .on() function

As a new comer to JS and jquery, I just can't seems to get this thing working! The alert gives undefined!
this.$el.on('click', '.chorse-item',{id:$(this).attr('id')}, this.handleItem);
this.handleItem = function(event) {
alert(event.data.id);
}
It shows the "id" perfectly with
this.$el.on('click', '.chorse-item', function(){alert($(this).attr('id'))});
I suspect the $(this).attr('id') is falling out of scope or something? cause
this.$el.on('click', '.chorse-item',{id:"Testing"}, this.handleItem);
Shows the "Testing".
No need to pass any data inside .on method, as it already available inside the calling function :
this.$el.on('click', '.chorse-item', this.handleItem );
this.handleItem = function(event) {
// `this` here != with the this `this.handleItem`
// this here would refer to this `.chorse-item` already
// so just calling it using `this.id` or `$( this ).attr( 'id' )`
// in order to get clicked element's id or anything else related
alert(this.id);
}
$(this) in your non-working version is in the context of the function registering the onclick handler. 'id' is undefined because it's not an attribute of the object you are in at the time, and you are assigning that undefined attribute to the id property of the data object.
$(this) in the second working version is in the context of the element calling the declared function.
Who's 'id' attr are you wanting to get access to? If it's the object that's clicked (which I suspect) then your second method is the way you want to be implementing this, and the first method is wrong for your purpose.

onclick attribute not working as expected

I have a jquery file as follow :
$('.font').click(function(){
for(i=0;i<FontArray.length;i++){
var font = FontArray[i];
$('#view_container').append("<button class='b_font' id='"+font+"' onclick='saveMe("+font+");'>"+font+"</button>");
$('.'+font).css('font-family',font);
}
// event.preventDefault();
});
And the function saveMe is defined as follow :
function saveMe(font){
alert(font);
}
But when i click any of the button i get the following error :
Uncaught ReferenceError: saveMe is not defined
Can anyone help me on this ?
Thanks in advance!
The line
onclick='saveMe("+font+");'
renders as
onclick='saveMe(arial);'
So when you click on it, it is looking for a variable arial not the string "arial". You need to quote it.
onclick='saveMe(\""+font+"\");'
Now for saveMe not being defined, that needs to have more context. When is saveMe defined? If it is inside of a document ready/window onload method, than you need to put it outside of it so it is available in window scope.
And the line
$('.'+font).css('font-family',font);
Should probably be
$('#'+font).css('font-family',font);
The most important thing is where the saveMe function is defined. onclick has only access to global scope and that's there the fuction would have to be for this solution to work.
That'd be a quick workaround:
window.saveMe = function (font){
alert(font);
}
However, you should note that cluttering global scope is usually undesirable and quickly leads to errors. It's better to attach events to selected elements by using .click(). In your code - you can attach the element and then bind click event to it.
var $button = $("<button class='b_font' id='"+font+"' onclick='saveMe("+font+");'>"+font+"</button>");
$('#view_container').append($button);
$button.click(function () {
alert($(this).attr('id'));
});
EDIT: As epascarello also pointed out - the string is not escaped properly
I'm guessing saveMe is out of scope, you probably put it inside the DOM ready handler.
As you're using jQuery, why not use it, and get rid of those inline event handlers
$(function() {
$('.font').click(function() {
$('#view_container').append(
$.map(FontArray, function(index, font) {
return $('<button />', {
'class' : 'b_font',
id : font,
on : { click : saveMe },
css : { fontFamily : font }
})
})
)
});
function saveMe() {...}
});
You could simply add this code and get rid of the code in the markup:
$('#view_container').on('click','.b_font',function(){
saveMe($(this).text());
});
OR perhaps better make this change:
$('#view_container').append("<button class='b_font' id='"+font+"' data-fontsave='"+font+"'>"+font+"</button>");
then this works and is less prone to error perhaps:
$('#view_container').on('click','.b_font',function(){
saveMe($(this).data('fontsave'));
});

Access "this" in Fuel UX placard onAccept function

I have several Fuel UX placards on a page, with a single jQuery selector to initialize them all. I need to write a custom onAccept function to handle placard confirmation.
It seems like I should be able to access $(this) from within the onAccept to access the element being initialized, but it just points to the window object.
How can I go about accessing the current element in a placard onAccept function?
Here's my code for reference:
$(".select-user-placard").placard({explicit: true, onAccept: function (helpers) {
DMSC.UpdateUser(DMSC.SelectedForm.Id, $(this).data("field-type"), helpers.value);
}});
I need to call this function passing a parameter that is retrieved from a data-attribute on the element, but I'm not sure how I can access the current element without the use of this.
I guess I was kind of thrown by the no access to this and I couldn't think of the obvious solution:
$(".select-user-placard").each(function (index, element) {
var $element = $(element);
$element.placard({explicit: true, onAccept: function (helpers) {
DMSC.UpdateUser(DMSC.SelectedForm.Id, $element.data("field-type"), helpers.value);
}});
});
Instead of calling placard on the jQuery selector, I iterate over each using jQuery's each and just use the jQuery iterator to select that element's data.

Using $(this) & event in named handler function

I have this function:
function showPost(event){
event.preventDefault();
$(this).parent('article').animate({width:'100%'}, 'slow');
}
I am attempting to use it like so:
$('.article-header').click(function(event){showPost(event);});
When I use it in the above manner, the event property is passed just fine, however $(this) doesn't work within the function. If I attempt to include this as a parameter in the .click method, it returns an error claiming this is undefined. I have even gone so far as to set var ths = $(this); to no avail.
Please, what is the proper way to make this function happen?
Just use the function directly:
$('.article-header').click(showPost);
You're loosing this because you're calling the function "naked", with no object receiver. You could do this too (but don't because there's no point here):
$('.article-header').click(function(event) { showPost.call(this, event); });

Categories

Resources