Reputation: 1240
I'm trying to build this section based on anchor navigation. When I click on a link I get to the desired anchor and the clicked link gains a class with a specific style, so far it works well:
HTML
<body>
<nav>
<div class="anchor-link" > <a href="#anchor1" > Anchor 1 </a> </div>
<div class="anchor-link"> <a href="#anchor2"> Anchor 2 </a> </div>
<div class="anchor-link"> <a href="#anchor3"> Anchor 3 </a> </div>
<div class="anchor-link"> <a href="#anchor4"> Anchor 4 </a> </div>
<div class="anchor-link"> <a href="#anchor5"> Anchor 5 </a> </div>
</nav>
<div class="main-wrap">
<div id="anchor1"></div>
<div id="anchor2"></div>
<div id="anchor3"></div>
<div id="anchor4"></div>
<div id="anchor5"></div>
</div>
</body>
JS
$(document).ready(function(){
$(".anchor-link").on("click", function(){
$(this).addClass("active");
$(this).siblings().removeClass("active");
Now I'd like to get the value inside the href but this does not work and it returns undefined:
var href = $(this).attr('href');
console.log(href);
})
Assuming it worked, and the var href holds the value of the clicked link, for example "#anchor1", how would I have to proceed to then find in the "main-wrap", the div with the id of "#anchor1"?
Would this work, and how would I have to fill that find query?
$(".main-wrap").find(...);
Upvotes: 3
Views: 27548
Reputation: 3928
Here is a jsFiddle doing what you want: jsFiddle
And there is the jquery snippet:
$(document).ready(function(){
$(".anchor-link").on("click", function(){
$(this).addClass("active");
$(this).siblings().removeClass("active");
var href = $("a", this).attr('href');
$(href).html("You clicked " + href + " !");
});
});
You where trying to get the href of the $(this)
element refering to the <div class="anchor-link" >
clicked, wich does not have any href
attribute.
By doing this: $("a", this).attr('href')
you tell Take the value of the href attribute of the <a>
element in the div I just clicked
After this you can select the corresponding div with $(href)
Upvotes: 5
Reputation: 171669
You are trying to get href
of a <div>
and it does not have that attribute
Change selector to the <a>
or look inside the div using find()
$(".anchor-link").on("click", function(){
var href = $(this).find('a').attr('href');
....
})
Upvotes: 3
Reputation: 750
Try the following click handler
$(document).ready(function(){
$(".anchor-link a").on("click", function(){
$(this).parents('.anchor-link').addClass("active");
$(this).parents('.anchor-link').siblings().removeClass("active");
var href = $(this).attr('href');
console.log(href);
});
})
Upvotes: 1