cgrouge February 2016

Anchor dropdown menu for options with hidden content

I have a drop down menu that I would like to add anchors to. The drop down has 4 options which are all hidden on start. When an option is clicked, that section will be visible. The drop down menu will have content above it and I need the page to move down when an option is clicked and becomes visible. How do I add anchors to these options?

I'm not well versed in javascript, but this is what I have:

<html>
    <head>
    <meta charset="utf-8"> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
        <script>
            $(document).ready(function(){
                $('#purpose').on('change', function() {
                    if ( this.value == '0'){
                        $("#value0").show();
                    } else {
                        $("#value0").hide();
                    }

                    if ( this.value == '1'){
                        $("#value1").show();
                    } else {
                        $("#value1").hide();
                    }

                    if ( this.value == '2'){
                        $("#value2").show();
                    } else {
                        $("#value2").hide();
                    }

                    if ( this.value == '3'){
                        $("#value3").show();
                    } else {
                        $("#value3").hide();
                    }
                });
            });
        </script>
    </head>
    <body>

    <!--Drop Down-->
    <p><select id="purpose">
    <option value="0">&nbsp;</option>
    <option value="1">1 column w/big hero</option>
    <option value="2">1 column w/s-curve</option>
    <option value="3">1 column; linear</option>
    </select></p>
    <!--End Drop Down-->

    <table width="100%" height="1000" cellspacing="0" cellpadding="0"        

Answers


Bob van Luijt February 2016

You can get the top level of the item your fetching.

var valueTop = $("#value0").offset().top; // what is the offset of the item
$(window).scrollTop( valueTop ); // set the window's scroll position

In your example:

$('#purpose').on('change', function() {
    if ( this.value == '0'){
        $(value0).show();
        var vtop = $("#value0");
        var valueTop = vtop.offset().top
        $(window).scrollTop( valueTop );    
    } else {
        $("#value0").hide();
    }
})

You can also animate the scrolling:

$('#purpose').on('change', function() {
    if ( this.value == '0'){
        $(value0).show();
        var vtop = $("#value0");
        var valueTop = vtop.offset().top
        $('html, body').animate({scrollTop: valueTop},500);
    } else {
        $("#value0").hide();
    }
})

Post Status

Asked in February 2016
Viewed 3,678 times
Voted 5
Answered 1 times

Search




Leave an answer