jQuery: $(this).attr('id') not find id of element - undefined - javascript

I'm trying to get id and just simply alert it onclick although is does just "undefined"...
Can you help me out?
important Code:
HTML:
<img src="/pictures/picture.jpg" class="r-gal-photo" id='1' onclick="alertme()" />
jQuery:
function alertme() {
alert($(this).attr('id'));
}
Can you see the problem? I can't...
My bad:
I'm sorry, I wanted to simplify the code and I did not realize that I used "alert()" as name for customized function.

First problem to fix is the function name, which I suspect is different in your actual code because otherwise you wouldn't have gotten as far as you have.
You've used an old-school "onclick" attribute to associate the function with the element. Nothing assures that this will be bound to the element as you expect. You could either change the element:
Better would be to use jQuery to bind the handler:
$("#1").on("click", function() {
alert(this.id);
});

The problem is, as others said - the context of the this keyword.
this refers to the DOM element (as you thought it does) in the CALL ITSELF, but once you called alertme() it is not defined in its scope.
To see it you can look at this JS:
function alertme(){
alert($(this).attr('id'));
console.log(this);
}
and this HTML markup:
<img src="/pictures/picture.jpg" class="r-gal-photo" id='abc' onclick="console.log(this); alertme()" />
And you will see that you get in the console first the element, then in the alert 'undefined' and then in the console the window.
To fix it you can either simply specify the meaning of this in the call, using javaScript's Function.prototype.call() function:
Change only in the HTML the markup to
<img src="/pictures/picture.jpg" class="r-gal-photo" id='abc' onclick="alertme.call(this)" />
and it will work with the your alertme().
OR you can just pass this into alertme like so:
function alertme(elem){
alert($(elem).attr('id'));
}
HTML:
<img src="/pictures/picture.jpg" class="r-gal-photo" id='abc' onclick="alertme(this)" />
Sources:
Nice article to understand 'this' in jQuery
this in JS binded by on markup

Related

What is "this" inside the event .on('click', 'class', function () {})

I try to have access to the row i clicked to add or remove a class, but it seems like i misinterpreted the value of this. Isn't it supose to be the DOM where the event go called (in this case, the <li>)? Here is my code:
JAVASCRIPT
$(document).on('click', '.ToDownload', function()
{
if($(this).className.lastIndexOf("isSelected") != -1)
{
$(this).addClass("isSelected");
$(this).css('border', '2px solid #000099')
}
else
{
$(this).removeClass("isSelected");
$(this).css('border', 'none')
}
});
HTML
<li id="addedDownloadFileRow" class="fitting ToDownload">
<a href="#">
<div class="ui-grid-a">
<div class="ui-block-a">test1</div>
<div class="ui-block-b">test2</div>
</div>
</a>
</li>
In fact, i thought i could use the property className to find if my row is already selected, but it seems like this isnt the DOM of the <li> tag. Any information or a way to see what this really is would be appreciated.
P.S. The class "fitting" is only used for some css purpose.
this is a DOM Element, $(this) is a jQuery object
Full working code is in http://jsfiddle.net/tomi77/xgv8q9md/
If you use Chrome (not sure whether this works in Firefox), you can log the value of this to the console.
If it is a jQuery object, it might not be clear to see which element it refers to, however it's straightforward to get the underlying element out.
console.log(this[0]);
This will give you a minimal representation of the element itself and if you hover over it, you'll see the element highlighted in the web view itself.
This lets you see exactly which element it refers to. As mentioned in the comments, you can also log the direct object form of the element to the console with console.dir(element).

Hide DIV element with onclick command

Thanks to anyone who helps me solve this issue.
So the issue is I'm trying to hide an element (by class) with an onclick event using a button. But I am unable to do so.
Here's the code on jsfiddle http://jsfiddle.net/1tpdgrnj/
Here's the code for those who wish to help me here:
HTML:
<div class="box">Hide on button click!!
<button onclick="close();">Close</button>
Javascript:
function close() {
document.getElementsByClassName("box").style.display = 'none';}
UPDATE
Refer to the answer below and to the jsfiddle to see how it's different.
See this fiddle
Change your javascript as follows
function myFunction() {
document.getElementsByClassName("box")[0].style.display = 'none';
}
First change that should be done is, rename your function name, as close is a keyword in Javascript.
Second one is that, document.getElementsByClassName() returns an array and thus to get the first element you should use the index position 0.
According to the docs
The Element.getElementsByClassName() method returns a live
HTMLCollection containing all child elements which have all of the
given class names. When called on the document object, the complete
document is searched, including the root node.
Read more about it here
You can use Jquery
<div class="box">Hide on button click!!
<button class="close">Close</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".close").click(function(){
$(this).parent().hide(); return false;
});
});
</script>
Check this fiddle
You can also do this easily with jQuery.
$("#hide").click(function(){
$(".box").fadeOut(150);
});

onClick populated by variable without triggering it

I want to append this to my document:
$('#myDiv).append("<div id='myDiv2' onclick="+extElementConfig.onClickDo+">Do</div>");
The snippet above has it's onClick populated by a certain object with properties,
this:
var extElementConfig={onClickDo:sampleFunc()};
Unfortunately declaring a function into the object property also fires it, as was expected.
How can I achieve the above functionality without triggering the
sampleFunc()?
I just need to dynamically populate the onClick event through an object property.
Assuming you have control over the extElementConfig object, remove the parenthesis from sampleFunc
var extElementConfig={extElementPosition :10,extElementId:'mailOrderBtn',onClickDo:sampleFunc};
As Rob. M. pointed out the real problem with your code was the fact you were running the code when it was in the object instead of assigning a reference. And when you tried to assigning the onclick, that had issues too since you are trying to use a function reference when it was a string.
To get your code to run, it would be something like
function sampleFunc () {
alert("clicked");
}
var extElementConfig={onClickDo:"sampleFunc()"};
$('#myDiv').append("<div id='myDiv2' onclick='"+extElementConfig.onClickDo+"()'>Do</div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myDiv"></div>
To get rid of this, do not use the sting method to build up the element, instead leverage the power of jQuery. Below is an example where I build a div and pass in some arguments to change the element's text and css when clicked.
function sampleFunc(txt, css) {
$(this).text(txt).css(css);
}
var extElementConfig = {
onClickDo: sampleFunc,
onClickArgs : ["Clicked", {"background-color":"green"}]
};
$('<div/>', {
id: 'myDiv2',
text: 'Do!'
}
).on("click",
function() {
extElementConfig.onClickDo.apply(this, extElementConfig.onClickArgs);
}
).appendTo("#myDiv");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="myDiv"></div>

What does "this" return in JS?

I have 2 questions
What does this refer to? I understand that it is some kind of container for the object in question.
I am trying to pass a variable using a form due to lack of better options. My idea was to have a <a onclick> and in the onclick, to have this.form.submit();
<form action="/justtesting/" method="post">
<a onclick="this.form.submit();" href="">click this</a>
<input name="pageid" value="12" type="hidden">
<input name="mid" value="5" type="hidden">
</form>
And that way I pass the variable.
I have seen this before but instead of <a> they used a button.
The short answer:
this refers to the object that called the function that is currently executing
The long answer:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/this
"this" without any context always refers to the -window- object.
var test = 123;
alert(test); // 123
alert(this.test); // 123
You'll want to have some sort of jQuery click event for that , searching for whatever value you want to pass along with the form submit.
this refer to the current element , in your case it refers to the A tag
if you use <Button type="Submit">click this</Button> then it will work without javascript
And if you use A tag then don't leave href attribute as it can cause problem
click this
inside of an in-line binding (e.g. onclick or onload attribute of an element), this refers to the element itself. So, for example:
Click me
<!-- Alerts "http://google.com" -->
<img src="foo.jpg" width="50" height="50" onload="alert(this.width+'x'+this.height);" />
<!-- Alerts "50x50" -->
So by saying this.form you're saying "grab the form that this element belongs to (if any)", then you're calling the form element's submit() method.
this when passed to an event
say refers to the anchor object passed to the function as param.
In the case of an event handler, 'this' refers to the target event in question
Example:
<div onclick="console.log(this) id="me">click me</div>
2. In the case of an object, it refers to the object in question
Example:
x = { hi: function(){console.log("Hi "+this.name)}};
x.name= "Bill";
x.hi(); // Hi Bill
3 Both these behaviours can be altered by calling a so-called binding, either by using bind, apply or call (bind is implemented here)
var bind = function(obj, fn){ return function(){ return fn.apply(obj, arguments)}
y.name = "Joe";
x.hi = bind(y, x.hi);
x.hi(); //Hi Joe
4 When no such is specified, this refers to a global object, which equals to window in browsers in compatibility mode, and to undefined in so-called strict mode.
In normal Javascript events, this refers to the element which the handler is bound to. However, if your event was bound with attachEvent in IE, this refers to the window. In your code, this refers to the clicked anchor tag. Here's how to properly implement your desired functionality in jQuery:
$("a").click(function() {
$(this).closest("form").submit();
});

this, current context-when should I use in jQuery?

I am not very sure with the use of "this" [current context] in jquery.What I know is- it prevents the dom from searching all the elements, it just work on that current element, which improve performance[correct me if I am wrong].Also I am not sure when to use this and when not.
lets say, should I go for
$("span",this).slice(5).css("display", "none")
or
$("span").slice(5).css("display", "none")
both will work, but I am not very clear as how really it works.can somebody explain it with a diff/proper example, and when to use what?
[EDIT]
$(function() {
$("#clickme").click(function() {
$("span",this).slice(5).css('display', 'block');//doesn't work ? why?
$("span").slice(5).css('display', 'block');//works..why?
});
});
enter code here <span id="clickme">Click me</span>
<span>itam1</sapn>
<span>itam2</sapn>
<span>itam3</sapn>
<span>itam4</sapn>
<span>itam5</sapn>
...upto10
Usually you can use the this keyword on event handlers since it will be a reference to the element that triggered the event and other jQuery functions like $.each.
For example when handling a click event lets say:
$('.parentElement').click(function () {
$('.foo', this).hide();
});
The above code, will hide all the elements with class foo that are descendants of the currently parentElement that was clicked.
The use of the context argument of the jQuery function is the equivalent of making a call to the find method:
$(expr, context);
// is just equivalent to:
$(content).find(expr);
EDIT: Looking at your example:
$("#clickme").click(function() {
$("span",this);//... (1)
$("span");//.. (2)
});
The first line, will look for all the span elements that are inside of #clickme (its descendants), since that element was the one that triggered the click event.
The second line, will look for all the span elements on the whole page.
How it works
Lets use this HTML for the examples:
<div id="container">
<div class="column">Link 1</div>
<div class="column">Link 2</div>
</div>
<div id="footer">
Link 3Link 3
</div>
The scoping parameter of the jQuery function should only be used if you already have a cached reference to a DOM element or jQuery wrapped element set:
var $set = $('#container');
$('a', $set).hide(); // Hides all 'a' tag descendants of #container
Or in an event:
$("#container").click(function(e){
$('a', this).hide(); // Same as call above
}
But it makes no sense to use it like this:
$('a', '#container').hide()
When it should be written like this:
$('#container a').hide();
Having said all that, it is generally cleaner and clearer to just use .find() instead of using the second parameter in the jQuery function if you already have the jQuery or DOM element. The first example I gave would be written this way instead:
var $set = $('#container');
$set.find('a').hide(); // Hides all 'a' tag descendants of #container
If this one call was the only reason you grabbed the #container object, you could also write it this way since it will still scope the search to the #container element:
$("#container a").hide(); // This is the same as $('a', "#container");
Why would you scope your selections
When jQuery looks for an unscoped selector, it will search through the entire document. Depending on the complexity of the selector, this could require a lot of searching. If you know that the element you are looking for only occurs within a specific parent, it will really speed up your code to scope the selection to that parent.
Regardless of what method of scoping you choose, you should always scope your selectors whenever possible.

Categories

Resources