Jquery / js closeest (). attr () returns undefined
I just recently started learning JS, jQuery, HTML and CSS. Right now I am trying to make my page when the class of the class is clicked, animate and then redirect to the link of the clicked item.
I looked around a lot and got the thing .closest(selector).attr('href')
or parent thing. I tried both and I just keep getting undefined forlinkto
HTML:
<div class="col-sm-4">
<div class="mainCon">
<a href="programs.html">
<li class="category">
<img style="height: 150px;" src="programs.png" /><br />
Programs
</li>
</a>
</div>
JS:
$('.category').click(function() {
$('.mainCon').animate({
right: '100px',
opacity: '0',
}, 500, function() {
var linkto = $(this).closest('a').attr('href');
location.href= linkto;
})
return false;
});
Any idea why it linkto
always returns undefined? The linked html file (program.html) is in the same directory as the page I'm about to navigate to, so I really don't know what happened.
source to share
Invalid HTML. li
there can only be a child element ul
,
Using
$('.category').click(function() {
var self = $(this); //Cache this in a variable
self.closest('.mainCon').animate({
right: '100px',
opacity: '0',
}, 500, function() {
var linkto = self.closest('a').attr('href');
location.href= linkto;
})
return false;
});
OR
$('.category').click(function() {
var self = $(this);
self.closest('.mainCon').animate({
right: '100px',
opacity: '0',
}, 500, function() {
var linkto = $(this).find('a').attr('href');
location.href= linkto;
})
return false;
})
source to share
Inside the animate callback this
is an element mainCon
. ... closeest () is used to find an ancestor element, but in your case you need to find a descendant element, so use . find ()
$('.category').click(function() {
$('.mainCon').animate({
right: '100px',
opacity: '0',
}, 500, function() {
var linkto = $(this).find('a').attr('href');
location.href= linkto;
})
return false;
});
Note. Your html is not valid, li
cannot be a childanchor
source to share
$ ('mainCon'). (this) object and $ ('. category') (this) object are different when you use $ (this) under
$('.mainCon').animate()
means you are in <div class="mainCon">
not<li class="category">
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('.category').click(function () {
// $(this) == $('.category')
$('.mainCon').animate({
right: '100px',
opacity: '0',
}, 500, function () {
// $(this) == $('.mainCon')
var linkto = $(this).find('a').attr('href');
/* alert($(this).find('a').attr('href')); return false; */
location.href = linkto;
})
return false;
});
});
</script>
</head>
<body>
<div class="col-sm-4">
<div class="mainCon">
<a href="programs.html">
<li class="category">
<img style="height: 150px;" src="programs.png" /><br />
Programs
</li>
</a>
</div>
</body>
</html>
source to share