简体   繁体   中英

Scroll to a particular div in jquery?

I have to scroll to a particular div onform submit (if there is any error). But it goes to the top of the window without showing the error message. Here is my code :

HTML

<form name="createProperty" method="POST" onsubmit = "return submit_new_property()">
    <select class="slt_box" name="property_type" id="property_type">
        <option>Select</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>
</form> 

JS

function submit_new_property() {
    var property_type = $('#property_type').val();

    if(property_type == 'Select' || property_type == '' || property_type == null) {
        document.getElementById("basic_info_error_div").innerHTML="Choose Property Type";
        document.getElementById("basic_info_error_div").style.display='block';
        $.scrollTo( $('#basic_info_error_div'), 500);
        return false;
    }
    else {
        document.getElementById("basic_info_error_div").innerHTML = "";
        document.getElementById("basic_info_error_div").style.display = 'none';
    }
}

You can use .scrollTop()

$('html, body').animate({
    'scrollTop' : $('#basic_info_error_div').position().top
}, 500);

OR

If you want vanilla JS, You can use Element.scrollIntoView

document.getElementById('basic_info_error_div').scrollIntoView(true);
  $('html, body').animate({
    scrollTop: $("#basic_info_error_div").offset().top
  }, 500);

You seem to be trying to use the jquery.scrollTo plugin. You need do download it from the releases page .

After that you can do:

$.scrollTo('#basic_info_error_div', 500);

And it will work as expected.

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM