Blainer Blainer - 7 months ago 9
Javascript Question

grabbing href tag on click

I am trying to grab the href tag on the element clicked in the "navigation" div
The current code returns "#BiblesandCommentaries" every time no matter what element I click in the navigation div.

html

<div class="navigation">
<ul>
<li><a href="#BiblesandCommentaries">الانجيل-تعليقات</a> </li>
<li><a href="#EnquirersLibrary">الاستفسارات</a> </li>
<li><a href="#NewBelievers">مؤمنون جدد</a> </li>
<li><a href="#ChristianLiving">حياة المسيحى</a> </li>
<li><a href="#FamilyLibrary">مكتبة الأسرة</a> </li>
<li><a href="#YoungAdultLibrary">مكتبة الشباب</a> </li>
<li><a href="#WorshipLibrary">مزامير وتراتيل</a> </li>
<li><a href="#BibleTeachings">التدريس</a> </li>
<li><a href="#Leadership">القيادة</a> </li>
<li><a href="#SchoolofChrist">مدرسة الإنجيل</a> </li>
<li><a href="#Dota">شاگرد سازی بصورت شنیدن</a></li>
<li><a href="#MinorityLanguages">فهم المسيح</a> </li>
</ul>
</div>


js

$('.navigation').click(function() {
test = $(this).find('a').attr('href');
alert (test);
});

Answer

using .find().attr() like that will always get the first one, you need to change the selector for your click function to target the a like this:

$('.navigation a').click(function(e) {
    e.preventDefault(); //use this if you don't want to reload the page
    var test = $(this).attr('href');
    alert (test);
}); 

also you should declare your variables.

EDIT ok commenters, I was just fixing his code, but here ya go:

$('.navigation a').on("click",function(){
       alert($(this).attr('href'));
});

EDIT haha commenters, let's get pedantic:

$("div.navigation").on("click", "a", function(e) {
    e.preventDefault();
    alert ($(this).attr('href'));
});​​​​

without preventing the default operation of the a tag, you'll be reloading the page

EDIT: Want to take it a step further? Forget jQuery. Here's some vanilla JS

document.querySelector("div.navigation").onclick = function(e){
    if(e.target.href){
        e.preventDefault();
        alert(e.target.href);
    }
}