I make a website with news, when you click on the read more button (the opening of the full news), the news is loaded from the php file via ajax and changes the window.location.hash to the id this news. How to make it so that when opening a link with an already existing window.location.hash this news opens?

The code that loads the news and assigns hash:

 $('.contentshortnews').on('click', '.full-opener', function(){ var newsid = $(this).attr('id'); $.post('http://jarwis-master.ru/php/newsget.php', { newsid: newsid }, function(data){ window.location.hash = 'news-'+newsid; $('.datanews').html(data); }); }); 

    2 answers 2

    To process the site loading event and check the existing hash in it. In order to execute the code after loading the site, there are many ways in jquery. One of them is this:

     $(function() { // this code will be executed on page load }); 

    Questions refactoring code to eliminate copypaste leave you.

    I also advise you to handle the hashchange event, so that when you manually (and not only) change the hash, the necessary page is also loaded. Only be careful with this - if you hang up too much, there is a danger of going into endless recursion, because when changing the hash with javascript, this event will also be raised. I recommend in the handler for clicking on read more not to load the page, but simply to change the hash, and to load the load to the hashchange handler. In other matters, I do not know all the details of your task - you may need other logic (for example, if you want to scroll to this news when you open it).

      Put the news load into a separate function, and check whether there is a window.location.hash at the start:

       $(function() { $('.contentshortnews').on('click', '.full-opener', function(){ readMore($(this).attr('id')); }); function readMore(newsid) { $.post('http://jarwis-master.ru/php/newsget.php', { newsid: newsid }, function(data){ window.location.hash = 'news-'+newsid; $('.datanews').html(data); } ); } if (window.location.hash) { readMore(window.location.hash.replace('#', '')); } });