Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go to certain part of page in jquery?

Is it possible to skip to a certain part of a page in jquery, for example I am on index.html and I want to go to the middle of the page on page2.html how do i make a link that does that? Thanks in advance for your answers. :)

P.S. I have to use jquery because thats what im using for the whole site so the whole #location-on-page will NOT work :) Thanks

Snippet 1:

<a href="page.html#1"><img src="image_location/1.jpg" width="95%" border="1"></a>

Snippet 2:

<a href="image_folder/1.jpg"><img src="image_folder/1.jpg"><br>
Description
<a name="1"></a>
like image 684
William Lewis Avatar asked Nov 18 '11 21:11

William Lewis


3 Answers

If you need to go to a specific anchor via Javascript and not by clicking an anchor tag on the page then use

location.href = "#anchor";

jQuery isn't needed in this case but if you wanted too, you could simply create your own custom jQuery function

$.fn.gotoAnchor = function(anchor) {
    location.href = this.selector;
}

$('#1').gotoAnchor();

// This way would also allow going to another pages anchors like so
$('page2.html#1').gotoAnchor();

or

$.fn.gotoAnchor = function(anchor) {
    location.href = '#' + this.selector;
}

$('1').gotoAnchor();

Depending on if you want to have to specifiy the anchor character # in your selector.

like image 150
Jeff Wilbert Avatar answered Nov 03 '22 07:11

Jeff Wilbert


You have to put an anchor in. No need for jQuery!

On page 2 - where you want it to jump to.

<a name="myanchor"></a>

On page 1.

<a href="page2.html#myanchor">Link</a>
like image 25
Daniel A. White Avatar answered Nov 03 '22 06:11

Daniel A. White


That is a feature of HTML, not jQuery, so will work with both.

On page2.html you need to include a named anchor tag where you want the page to go to...

<a name="half-way">&nbsp;</a>

Then in index.html, you can use an anchor tag that points there...

<a href="page2.html#half-way">This should get you half way..!</a>

You could use jQuery to generate these tags if you wanted to.

like image 32
Billy Moon Avatar answered Nov 03 '22 07:11

Billy Moon