The main idea of creating this function is not to use the vertical scroll, and from a click event of a button or other control execute this function and navigate to a% tag <div>
or a label <a>
specify that it is in the same page.
The main idea of creating this function is not to use the vertical scroll, and from a click event of a button or other control execute this function and navigate to a% tag <div>
or a label <a>
specify that it is in the same page.
To navigate within the same page you must use an element with id (the goal) and an anchor ( <a>
) that points to that element, as follows:
<a href="#id_del_elemento">Ir a tal parte</a>
...
<div id="id_del_elemento"> ... </div>
The target element can be any element.
<a href="#elid">Ir a el ID</a>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p id="elid">este es el elemento</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
To do the same in javascript, you can do the following: Here the trick is that you set the hash of the url in the value of the id of the element, just as if you edited it by hand in the bar of the browser URL.
function moverseA(idDelElemento) {
location.hash = "#" + idDelElemento;
}
and you use it
moverseA("id_del_elemento"); // sin el #
function moverseA(idDelElemento) {
location.hash = "#" + idDelElemento;
}
<button onclick="moverseA('elid')">Ir a el ID</button>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p id="elid">este es el elemento</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
<p>lorem</p>
The rnd response is what you want. I'm going to leave an alternative with Javascript (using jQuery) in which the scroll is animated so that there is no jump to the target element, but a small transition is made by moving using animate
:
function saltarA(id, tiempo) {
var tiempo = tiempo || 1000;
$("html, body").animate({ scrollTop: $(id).offset().top }, tiempo);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p><a href="javascript:saltarA('#destino')">Saltar a destino</a></p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>0</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>0</p>
<p id="destino">Destino!</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>0</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>0</p>