Beniamino_Baggins Beniamino_Baggins - 4 months ago 8
Javascript Question

Call function designed for html <a> tags from javascript

I have this function that I found online that causes the href in my tags to be scrolled to rather than just appear there:

$(function () {
var headerHeight = 70;
$('a[href*=#]:not([href=#])').click(function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - headerHeight
}, 1000);
return false;
}
}
});
});


Now I need to get to a location in the page by using javascript code because I have an awkward situation where the form submit button should also scroll to a location:

<div
value="GO"
id="go-div"
class="bubble">

<input type="submit"
value="GO"
id="go-button"
style=" position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;"

onclick="location.href='#search-results-page';">
</input>
</div>


So how do I change the
location.href='#search-results-page';
to use the scrolling function?

cem cem
Answer

Multiple ways to do that. Here is an example: https://jsfiddle.net/nx7xf1nb/

$(function () {
    var headerHeight = 70;
    $('a[href*="#"]:not([href="#"])').click(function () {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            if (gotoTarget(this.hash))
                return false;
        }
    });

    $('input[data-target]').click(function() {
        if (gotoTarget($(this).data("target")))
            return false;
    })

    function gotoTarget(targetName) {
        var target = $(targetName);
        target = target.length ? target : $('[name="' + targetName.slice(1) + '"]');
        if (target.length) {
            $('html,body').animate({
                scrollTop: target.offset().top - headerHeight
            }, 1000);

            return true;
        }

        return false;
    }
});

Button:

<input style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;"
       type="submit" 
       data-target="#search-results-page"
       value="GO"
       id="go-button">