0

I'm using the following code to link to a section on a page.

$('a[href^="#"]').on('click', function (event) {
    var target = $(this.href);
    if (target.length) {
        event.preventDefault();
        $('html, body').animate({
            scrollTop: target.offset().top
        }, 1000);
    }
});


<a href="#group1" class="save">Save 20%</a>

The link is positioned absolute on the bottom right of the screen; Is there a way I can change the link on click? So that When you Click <a href="#group1" It scrolls to that section and then the same link becomes #group2, and then becomes #group3

isherwood
  • 58,414
  • 16
  • 114
  • 157
Nicholas Padula
  • 173
  • 1
  • 9

2 Answers2

0

This fiddle should do the trick.

I grabbed the current href value, incremented it by one and replaced it:

$('a[href^="#"]').on('click', function (event) {
    var target = $(this.href);
    if (target.length) {
        event.preventDefault();
        $('html, body').animate({
            scrollTop: target.offset().top
        }, 1000);
    }
    var idx = $(this).attr('href').slice(6);
    var newIdx = (idx)%3+1;
    $(this).attr("href",'#group'+newIdx);
});

You can see on mouseover that the link is changing (you have to move off and back on to see the change in most browsers).

kaz
  • 1,190
  • 8
  • 19
  • THANK YOU THANK YOU! I can't upvote because of reputation but this did what I needed! thank you so much! – Nicholas Padula Jun 04 '15 at 19:23
  • how would i add the slow scroll back into it? I can't get that to work properly. sorry for the trouble! – Nicholas Padula Jun 04 '15 at 19:35
  • I added that back in (but not in the fiddle, since I don't have your whole page). I think you should be able to upvote and mark your own question answers as correct - I didn't think that was a restricted privilege. – kaz Jun 04 '15 at 19:49
0

HTML

<a href="javascript:void(0);" data-href="#group1" class="save">Save 20%</a>

<div id="group1"></div>
<div id="group2"></div>
<div id="group3"></div>

JS

var i=1;
$('a').on('click', function (event) {
    i++;
    var anchor = $(event.target);
    var target = $($(event.target).data("href"));
    console.log(target);
    event.preventDefault();
    $('html, body').animate({
        scrollTop: target.offset().top
    }, 1000);
    anchor.data("href","#group"+i);
});

Answer working live on fiddle http://jsfiddle.net/rLpez4sp/1/

You can check the Javascript console for the link change.

Tarun
  • 195
  • 10