Matthew
Matthew

Reputation: 683

jQuery: Forward to url #link2 when people click on #link1

Let's say someone clicks on:

<a href="#" class="filter">Stillness Furniture</a>

The link in the browser will just go to whatever.com/page/#

Here is the code housing that link:

<nav id="portfolio-filter">
    <ul>
        <li class="filter"><a href="#" class="filter">View All</a></li>
        <li class="filter"><a href="#" class="filter">Stillness Furniture</a></li>
    </ul>
</nav>

I want the link to go to #portfolio-filter instead of just #, now obviously I could change the link href, but this is a WordPress theme and editing it would mean I have to change it every time I update the theme.

How would I be able to make the browser jump down to id#portfolio-filter when someone clicks that link?

Something like this is all I have so far?

$(document).on("click", "a.filter", function(){
   //do something
});

(taken from Onclick function based on element id)

Thanks in advance for any help.

Upvotes: 0

Views: 57

Answers (2)

gaetanoM
gaetanoM

Reputation: 42054

I may propose you, without changing nothing to your anchor:

$(function () {
  $('a.filter').on("click", function( e ) {
    e.preventDefault();
    var offset = $('#portfolio-filter').offset().top;
    var visible_area_start = $(this).offset().top;
    var visible_area_end = visible_area_start + window.innerHeight;
    if(offset < visible_area_start || offset > visible_area_end) {
      $('html,body').animate({scrollTop: offset - window.innerHeight/3}, 1000);
    }
  });
});
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>

<p>a</p><br>
<a href="#" class="filter">Stillness Furniture</a>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<p>a</p><br>
<nav id="portfolio-filter">
    <ul>
        <li class="filter"><a href="#" class="filter">View All</a></li>
        <li class="filter"><a href="#" class="filter">Stillness Furniture</a></li>
    </ul>
</nav>

Upvotes: 1

Taplar
Taplar

Reputation: 24965

So it seems like you want them to all go to the same place, if I understand you correctly. So you could rewrite the links if you wanted to...

$('#portfolio-filter').find('a.filter').attr('href', '#portfolio-filter');

Upvotes: 1

Related Questions