itmilos itmilos - 5 months ago 8
HTML Question

How to create an HTML button that acts like a link to an item on the same page?

I would like to create an HTML button that acts like a link to an item on the same page. So, when you click the button, it redirects to item on the same page.

How can I do this? (I would limit the solution to HTML, CSS, and JavaScript, because currently I am not using any other language)

Current Button (Bootstrap):

<a class="btn btn-large btn-primary" href="">Democracy</a>

Answer

This is assuming that you are not talking about scrolling down to a regular anchor, and instead you want to scroll to actual HTML elements on the page.

I'm not sure if jQuery counts for you, but if you're using Bootstrap, I imagine it does. If so, you can bind to the "click" event for your button and put some javascript code there to handle the scrolling. Typically you might associate the link/button with the element you want to scroll to using a "data" attribute (e.g. data-scroll="my-element-id").

Without jQuery, you'll have to make a function that contains the code as described, and put in an onclick attribute that references your function, and passes "this" as a parameter to your function, so you can get the reference to the link/button element that called it.

For the code to use to actually scroll to the corresponding element, check out this article:

How to go to a specific element on page?

Quick example without jQuery:

<a class="scrollbutton" data-scroll="#somethingonpage" 
 onchange="scrollto(this);">something on page</a>

<div id="somethingonpage">scrolls to here when you click on the link above</a>

<script type="text/javascript">
    function scrollto(element) {
        // get the element on the page related to the button
        var scrollToId = element.getAttribute("data-scroll");
        var scrollToElement = document.getElementById(scrollToId);
        // make the page scroll down to where you want
        // ...
    }
</script>

With jQuery:

<a class="scrollbutton" data-scroll="#somethingonpage">something on page</a>

<div id="somethingonpage">scrolls to here when you click on the link above</a>

<script type="text/javascript">
    $(".scrollbutton").click(function () {
        // get the element on the page related to the button
        var scrollToId = $(this).data("scroll");
        var scrollToElement = document.getElementById(scrollToId);
        // make the page scroll down to where you want
        // ...
    });
</script>

Note: If you literally want a "button" rather than a "link", you can really use any element and make that clickable, e.g.:

<button class="scrollbutton" data-scroll="#somethingonpage">something on page</button>
Comments