Search code examples
javascriptjquerybuttonscrollsmoothing

Smooth scrolling on button click


I used this code:

$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();
    var target = this.hash,
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 1000, 'swing', function () {
        window.location.hash = target;
    });
});

and the smooth scroll work perfectly between a link and an anchor!

But how can I make following button code work for ?

<input type="button" value="btn">

Solution

  • You can use like this:

    $('input[type="button"][value="btn"]').on('click',function (e) {
    

    If you need both separate them by a coma:

    $('a[href^="#"], input[type="button"][value="btn"]').on('click',function (e) {
    

    But I would strongly recommend to use a common class for them and access like this:

    $('.common_class').on('click',function (e) {