"this" not working as expected - javascript

I've been struggling with this for an hour now, and I can't solve it. I'm new to use this on javascript, but this is really simple, and it's just not working.
Here's the HTML
<ul class="nav pull-right nav-tabs" id="primarynav">
<li class=" navlink">
About
</li>
<li class="navlink active">
Portfolio
</li>
<li class="navlink">
Contact
</li>
</ul>
And the js
$(document).ready(function(){
$(".navlink").click(function(){
$(".navlink").removeClass("active");
this.addClass("active");
});
});
So it should remove class active from all elements with class navlink, and then add class active to the clicked element. But it doesn't.
http://jsfiddle.net/Tckf7/

Change it to:
$(this).addClass("active");
jsFiddle example
.addClass() is a jQuery method and you had been trying to apply it to a non-jQuery object (this vs $(this)).

this refers to the DOMElement to which jQuery has attached the event. To turn it into a jQuery collection and be able to use jQuery methods like addClass, pass it as an argument to $:
$(this).addClass("active");
Inside functions, the this keyword actually refers to the context of the function. In the case of event handlers, the context is the DOMElement that the handler is attached to.

addClass() is a jQuery method but this is just the direct reference to the DOM object. You need to wrap this into a jQuery object first before you can use a jQuery method on it.
$(document).ready(function(){
$(".navlink").click(function(){
$(".navlink").removeClass("active");
$(this).addClass("active");
});
});
DEMO - Using $(this).addClass() instead of this.addClass()
Edit
To elaborate a little on this. You can never call jQuery's addClass() method on a JavaScript object as addClass() is a jQuery method.
To do the same in pure JavaScript, if you want to just use this, you could use element.className, similar to this:
$(document).ready(function(){
$(".navlink").click(function(){
$(".navlink").removeClass("active");
//$(this).addClass("active");
this.className += " active";
});
});
DEMO - Using this.className example
Though if you are using jQuery already it would make little sense not to use $(this).addClass() instead.

this isn't a jQuery object, use $(this) instead.

You should use $(this)
$(document).ready(function(){
$(".navlink").click(function(){
$(".navlink").removeClass("active");
$(this).addClass("active");
});
});
http://jsfiddle.net/Tckf7/2/

Related

How to select element inside button using jQuery

What I'm trying to do is, to change i's class (which located inside button) on click
<button><i class="fa fa-square-o"></i></button>
Using js code like below (inside on click function):
...
$(this).child("i.fa").removeClass("fa-square-o");
...
getting child is not a function error
What am I doing wrong?
Yes, really there is no child() method in jQuery.
You may use find() or children() for that.
$(this).children("i.fa").removeClass("fa-square-o");
You could use find() instead.
$('button').click(function() {
$(this).find("i.fa").removeClass("fa-square-o");
});
Fiddle
child is not a function.
try this function:
$(this).children("i.fa").removeClass("fa-square-o");
jQuery accepts a second argument as context:
$('button').click(function() {
$('i.fa', this).removeClass('fa-square-o');
});
You are looking for jQuery .children() function. If you are trying to call that function from onclick attribute, you have to remember to pass reference to object by using "this" word.
<button onclick="removeClass(this)"><i class="fa fa-square-o">test</i></button>
removeClass = function(obj){
$(obj).children("i.fa").removeClass("fa-square-o");
}
Working fiddle:
http://jsfiddle.net/4wvgvzL9/

How can i change "this" class name with javascript?

I have a list of button with all latin-alphabet and i want to change the class name from "m_letter" to "m_letter active" for example so i can toggle them.
My javascript code is this
$(".m_letter").click(function(){
$(this).className = "m_letter active"; //This is an example i tried other codes that i found on net.
});
Html
<li class="m_letter">A</li>
<li class="m_letter">B</li>
<li class="m_letter">C</li>
...
<li class="m_letter">Z</li>
Use addClass
This will add the class on click:
$(".m_letter").click(function(){ $(this).addClass('active'); });
If you need to remove the active class from a different m_letter first, add this line.
$('.m_letter.active').removeClass('active')
Use .addClass()
$(this).addClass('m_letter active');
Since you're using jQuery, it's easy:
$(this).addClass('active');
inside your click handler.
Don't use:
$('.m_letter').addClass('active');
as that will set all of the items to active.
I think what you are looking for is this: http://jsfiddle.net/CKW25/1/
JS
$(".m_letter").click(function(){
$(".m_letter").removeClass("active");
$(this).addClass( "active" );
});

Not Able To assign click event

I have following html code. In my page there are many tag which have class='posta' but what i want assign onclick event only to which have post attribute.
<ul class="posts_li">
<li>
Post
</li>
<li>
Act
</li>
<li>
Event
</li>
<li>
Create News
</li>
</ul>
My Jquery Code for assigning an event is here
$(".posta").click(function(){
alert("here");
if($(this).attr("post")){
alert($(this).attr("post"));
}
});
$(".posta[post]").click(....);
Fiddle: http://jsfiddle.net/maniator/LmrPR/
Then use [attribute=value] in the selector:
Example
$('.posts_li').on('click', '.posta[post]', function() {
alert($(this).attr("post"));
return false;
});​
Additionally, you can avoid placing an event handler for each item by delegating them to the parent. In this example, I placed a single handler on the <ul> for all child elements using the .on() method (jQuery 1.7+). For older jQuery (1.4.2+), .delegate() is also available.
Use can use attribute selectors [propertyname] to select only nodes that have that property.
$(".posta[post]").click(function(){ ... });
You can do this with the css/jquery attribute selector:
$(".posta[post]").click(......... your code here)
Here's the example:
http://jsfiddle.net/wHvkF/
I would accomplish it using:
See this working Fiddle example. the last from the list doesn't alert
$(".posta[post]").click(function(e) {
e.preventDefault();
alert("here");
});
Works since version 1.0 of jQuery.

Using jquery 1.4 or javascript how would I target a specific link using a variable

HTML:
I've attached a simplified example of the problem I'm facing:
<h2>Product2</h2>
<div id="products">
<a class="my-product1" href="#"><span>my-product1<span></a>
<a class="my-product2" href="#"><span>my-product2<span></a>
<a class="my-product3" href="#"><span>my-product3<span></a>
<a class="my-product4" href="#"><span>my-product4<span></a>
<a class="my-product5" href="#"><span>my-product5<span></a>
</div>​
Javascript:
I'm already pulling myProduct from the page title and forcing lowercase. Next I'm attempting to remove this product from the group of links based on its class. Its quite possible this is jquery101 however I can't figure out how to add a class to a link using a variable to determine which class to select. In this example lets assume var myProduct = Product2
function removeProduct(myProduct){
$("a.myProduct").addClass("display-none");
};
Also, I am still learning so if you have the time a Brief explination of why what i'm doing is wrong would go a long way. Thanks for your time!
Simply concat the class name to the selector string:
$("a."+variable)...
Extra info as you requested:
Don't use a class "display-none"... change it's name or use jQuery native code that hides elements(hide(docs))
function removeProduct(myProduct){
$("a." + myProduct).hide();
};
Changing css rules is with the css(docs) function:
function removeProduct(myProduct){
$("a." + myProduct).css('display', 'none');
};
Adding class is with addClass function:
function removeProduct(myProduct){
$("a." + myProduct).addClass('someClass');
};
Change myProduct and removeProduct names to more meaningful variable names:
function hideAnchorElement(className){
$("a." + className).hide();
}
The class attribute / property is used as a generic selector - ie you can apply a class to multiple objects ... the id attribute / property is used for specific selection - and are unique. I suggest you change your HTML to use ids instead of classs
Try something like :
function removeProduct(myProduct){
$("a."+myProduct).css("display","none");
};
uses .css() to change the display property to none
or
function removeProduct(myProduct){
$("a."+myProduct).hide();
};
.hide() does the same thing as the .css() method does above
or
function removeProduct(myProduct){
$("a."+myProduct).addClass("yourclass");
};
where yourclass is a class you want to apply to an element.
And may I suggest you take a look at How jQuery works
Are you looking for this:
function removeProduct(myProduct){
$("a."+myProduct).addClass("display-none");
};
Separating the string selector from the variable
Try this if you want to hide the link on click event
$(function(){
$('#products a').on('click', function(e){
e.preventDefault();
$(this).hide();
});
});​
A fiddle is here.

How can i know which class was selected via jQuery & JS

I have a list with links:
<li class="link-1">One</li>
<li class="link-2">Two</li>
<li class="link-3">Three</li>
..
user clicks on any link, then with jQuery I want to display the content of the link.. somthing like:
$(".link-??? a").click(function() {
alert($(".link-??? a").html());
})
something like this. I am not going to create X function (as the number of the links), so what can I do? I should replace the ??? in somtehing else..
You could do:
$('li[class^="link"] a').click(...
However this would only work if the li have only one class or if the link-X class is the first in the list.
Inside the handler you can use $(this) to refer to the a element:
alert($(this).text());
Much better would be to give the li elements a common class:
<li class="link">One</li>
<li class="link">Two</li>
<li class="link">Three</li>
$('.link a').click(... will be much more reliable.
Give each element the same class. Then in your javascript reference this within your function. Check out the link below to see a working example
http://jsfiddle.net/kprgr/2/
<li class="link">One</li>
<li class="link">Two</li>
<li class="link">Three</li>
$(".link").click(function() {
alert($(this).find("a").html());
});
Try..
$(".link-??? a").click(function() {
alert(this.innerHTML);
})
Inside the click event, this should refer to the element that was clicked.
You could also do..
alert($(this).html());
..but the first way is simpler, and faster.

Categories

Resources