Prashant Singhal Prashant Singhal - 3 months ago 9
HTML Question

Jump to an element from a link not containing that element's id and on a different page

Pre-requisite knowledge:



In my website's footer, there are links that redirect user to the website's company page, say www.example.com/company.html#first .

Clicking this link would trigger the default browser behavior i.e. it will redirect to www.example.com/company.html#first and bring into view the div with id = "first".

But in my company.html's dom, there is no div with id = "first" (I have got my reasons due to which I can't provide the id to the concerned div but that's a separate issue). Moreover, I am using the url's hash in some functionality due to which I'm bound to keep it to #first.

Question:



So, my question would be if I can bring a different div into view - the parent element (which has an id available) of the div I failed to provide the id for as mentioned above on the click of the footer link. Suggestions are welcome as well!

Answer

So I did solve my own problem but only by hardcoding the url hash available. It's kind of dirty and the script would be called on every page but I think that's what I will use for now. I use $(document).ready() like this:

$(document).ready(function() {
if (location.pathname.split('/')[1] === 'company.html' && $.inArray(location.hash.split('#')[1], ['first', 'second', 'third']) > -1) {
  $('#parent').get(0).scrollIntoView();
}
});