Dranreb
Dranreb

Reputation: 107

Apply button javascript to an a href

My friend gave me this code that will allow a smooth scroll effect to the page once the user pushes an anchor button:

<form id = "button_design" action="#page2">
     <input type="submit" class="anchor-button" value="Page 2" />
</form>

And the javascript:

$(function() {
$('input.anchor-button').click(function(e) {
e.preventDefault();
var hash = $(this).parent('form').attr('action');
var target = $(hash);
target = target.length ? target : $('[name=' + hash.slice(1) +']');
if (target.length) {
  $('html, body').animate({
   scrollTop: target.offset().top
 }, 1000);
}

});
});

It works for input type = "submit" only and I want to try to use this code to my <a href ="#page3"... which is only a link and not a button. Can anyone help me to convert the code to make it apply to a href too? I tried messing around with it but I get nowhere.

Upvotes: 0

Views: 218

Answers (2)

Alex Slipknot
Alex Slipknot

Reputation: 2533

You really have to learn about selectors to work with JS. Here is an example with link. Every link must has class anchor and target in it's href attribute. So you don't need a form to wrap it:

<a class="anchor" href="#page2"> Page 2 </a>

And script for this markup

$(function () {
    $('a.anchor').click(function (e) {
        e.preventDefault();
        var hash = $(this).attr('href');
        var target = $(hash);
        target = target.length ? target : $('[name=' + hash.slice(1) + ']');

        if (target.length) {
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);
        }
    });
});

Upvotes: 1

Neil
Neil

Reputation: 14313

If you change the tag to a (both in jQuery and HTML) the code functions basically the same. Example:

$(function() {
$('a.anchor-button').click(function(e) {
e.preventDefault();
var hash = $(this).parent('form').attr('action');
var target = $(hash);
target = target.length ? target : $('[name=' + hash.slice(1) +']');
if (target.length) {
  $('html, body').animate({
   scrollTop: target.offset().top
 }, 1000);
}

});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id = "button_design" action="#page2">
     <a class="anchor-button" href="javascript:void(0)"> Page 2 </a>
</form>

<div style="height:800px; background-color:blue;">&nbsp;</div>
<div name="page2">test</div>

Upvotes: 2

Related Questions