Javascript function when url has #name appended

337 views Asked by At

I have a news ticker that I added hrefs to that are acting as anchors to html names. Once you click on one href the url gets the #name added to it. Here is the news ticker with the href #names...

<div id="ticker-wrapper" class="no-js">
<ul id="js-news" class="js-hidden">
    <li>
        <a href="#boxone">text</a>
    </li>
    <li>
        <a href="#boxtwo">text</a>
    </li>
</ul>

When you click one of the links it goes to the html name that looks like this...

<a name="boxone"></a>

All works well except my ticker ignores the all the settings it had like speed and opacity. My solution was to use a function to reset the news ticker when a #name is added to the url. So initially when my url is...

www.blah.com/users/1

My news ticker is working well. Then if you click a href in the news ticker the url changes to...

www.blah.com/users/1#boxone

And all the news ticker settings stop working. My function to reset the ticker is...

<script type="test/javascript">
function restartTicker() {
  // play ticker
  settings.play = true;
  settings.paused = false;
  // start the ticker again
  postReveal(); 
}

Question How do you call the function when the #name is added to the url? Thank you

EDIT I tried adding the onhashchange. Is this correct? I am wondering if the function is not working as desired.

<script>
if ("onhashchange" in window) {

$.fn.ticker.defaults = {
    speed: 0.10,            
    ajaxFeed: false,
    displayType: 'fade',
    htmlFeed: true,
    debugMode: true,
    controls: true,
    titleText: 'Latest News: ',     
    pauseOnItems: 3000,
    fadeInSpeed: 300,
    fadeOutSpeed: 300
};  
}
</script>
2

There are 2 answers

3
Michael Tang On BEST ANSWER

Check out the window event, onhashchange.

1
zungaphobia On

You want to listen to the window.onhashchange event.

https://developer.mozilla.org/en-US/docs/Web/API/Window.onhashchange