make the focus on a particular div after button click

Regularly, you can not focus a div. But if you will add a tabindex to it, it will work:

<div tabindex="0">test </div>

Here is a demo:

.z{margin-top:800px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" onclick="$('.z')[0].focus()" value="test" />
<div>
    <div class="z" tabindex="0">test </div>
</div>

If you click on test button div should became focused and jump into view. On click I just do something like divElement.focus()

Another option is just to scroll area which contains your newly added div, like in other answers here.


Using the following statement works for me.

document.getElementById('id').scrollIntoView();

You can use code like this to jump to the div

$(window).scrollTop($('#new_div').offset().top-20)

You can scroll to the top of the page with :

window.scrollTo(0,0);

or with jQuery using :

$('html,body').scrollTop(0);

Or with some fun effect

$('html, body').animate({ scrollTop: 0 }, 'fast');

Tags:

Javascript