0

I'm trying to find the <a> tag that is clicked, save its href attribute to an array and print out array.

Problem: The array seems to be saving the values of hrefs, however it doesn't display it when i try to use a for loop. It only displays all the values inside array when the for loop is inside on click event handler (and i don't want to print for loop there). Ideas?

      $(document).on('click', 'a', function () {
         var url = $(this).attr('href')
         hrefTracker.push(url);

      });

    for (var i = 0; i < hrefTracker.length; i++) {
        console.log(hrefTracker[i]);
    } 
1
  • In addition to what 'Wais' posted, every time a link is clicked a new page will load (unless they are only anchor links). You might want to do something like: ` $(document).on('click', 'a', function (event) { event.preventDefault(); ...` Commented Mar 11, 2017 at 7:06

1 Answer 1

1

Surely, your code won't work. Here is why:

You have first assigned an event listener to listen for clicks on <a> elements. The code inside the event listener will only run when an <a> element is clicked, however, the for loop will ONLY run when your webpage loads, AND WILL NOT RUN WHEN AN <a> ELEMENT IS CLICKED. You really need to place the for loop inside the event listener, like this;

var hrefTracker = [];
$(document).on('click', 'a', function() {
  var url = $(this).attr('href');
  hrefTracker.push(url);
  for (var i = 0; i < hrefTracker.length; i++) {
    console.log(hrefTracker[i]);
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0)">Some links</a>
<br>
<a href="javascript:void(1)">Some links</a>
<br>
<a href="javascript:void(2)">Some links</a>
<br>
<a href="javascript:void(3)">Some links</a>
<br>

Notice you have also omitted a semicolon after the line that reads var url = $(this).attr('href').

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer, i see your point. However, the whole point of an array to save hrefs when an anchor tag is clicked is to use save the hrefs and use it later i.e. outside of event handler function. For example: how would I access the array values and display it outside of the onclick function?
You are welcome. Notice that in my code hrefTracker is a global variable, so you can access it from anywhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.