jquery or js detect when hit enter on same hashcode url on address bar

扶醉桌前 提交于 2019-12-11 06:17:23

问题


I have a page with sticky menu bar in top. There are some internal links on this page. when I click on internal link, page scrolls and element having hashcode id moves to top. but heading hides in sticky menu. So on window load I have written js code, see below:

if(window.location.hash) {
        var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
        console.log (hash);
        if(hash && $("#"+hash).length){
            $("#"+hash).css('padding-top', '80px');
        }
        $(window).scroll(function() {
            $("#"+hash).css('padding-top', '0');
        });
    }

its working fine when page loads with hashcode url.

Problem is that when user click on address bar and without changing anything press enter, then element having id as hashcode agian moves to top and this time my js code not run and heading is hides in sticky menu.

So is there any way to detect this event when address bar is focused and enter key is pressed?

or is there any other solution for this situation?

Thanks,


回答1:


I came to a simple solution with the following logic. Be aware that i currently don't completely know in which other circumstances the 'focus' event in the window object is fired. I will update my post if i encounter side effects.

As far as i found out, Chrome does a full page load where Firefox just does what your description said. Thus the focus event in Chrome is fired BEFORE the page reloads, which should be considered into your implementation. (I have the repositioning logic within 'DOMContentLoaded' too, so this case is fine for me)

window.addEventListener('focus', function() {

    // Do the repositioning actions

});

Update

The focus event is also fired if you:

  • click at the title bar
  • minimize and maximize the browser window
  • switch programs in task bar and switch back to the browser


来源:https://stackoverflow.com/questions/39307241/jquery-or-js-detect-when-hit-enter-on-same-hashcode-url-on-address-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!