-6

I used this function for checking the url

<script type="text/javascript">
    $(document).ready(function () {
        if (window.location.href.indexOf("franky") > -1) {
            /* some code to change the css */;
        }
    });
</script>

Currently it only works when I refresh the page.

Is there a way to make it work when url change without any refresh ? Thanks

EXAMPLE : its like you have to choose a color , you click on a button to select your color , it make example.com/color.html#/red ; example.com/color.html#/blue ; example.com/color.html#/black only the color change with no refresh and i want to add specific css when url contain each string color

Mr Stark
  • 3
  • 1
  • 6
  • 1
    To clarify - did you want to change the URL? currently your code just tries to inspect it. – scunliffe Feb 21 '17 at 14:55
  • _is there a way to make it work so that the url changes without any refresh_ what would be the point? If you're trying to store state somewhere the URL is not the right place for it. – Yuck Feb 21 '17 at 14:57
  • I think this means getting the changed URL from `history` after pushing to it e.g. http://stackoverflow.com/questions/32828160/appending-parameter-to-url-without-refresh – G0dsquad Feb 21 '17 at 14:57
  • no i dont want to change it ! i want to add custom css by specific url contain string ! it work only on refresh page but when the url change without refresh nothing appear – Mr Stark Feb 21 '17 at 14:58
  • 1
    It sounds like you're trying to detect specific users based on the URL, and then use different CSS? If so, this is not a good way to achieve what you want. – Yuck Feb 21 '17 at 15:00
  • if you have php, try using $_SERVER['REQUEST_URI'] – Nomistake Feb 21 '17 at 15:03
  • in example my url change to example.com/test/27-black/22-coffee to example.com/test/26-white/22-coffee without refresh. i want to check when url contain white , or when contain black and apply css – Mr Stark Feb 21 '17 at 15:04
  • define the wanted css and change or add the id or class with $( "p" ).addClass( "yourClass" ); The corresponding css wil be applied. https://api.jquery.com/addclass/ – Nomistake Feb 21 '17 at 15:11
  • but i want to add it on specific url contain string – Mr Stark Feb 21 '17 at 15:12
  • Perhaps you just need to go about this a different way, take a look at this previously [answered question](http://stackoverflow.com/questions/3522090/event-when-window-location-href-changes) and subscribe to the `popstate` event. I have not personally used it before, but it seems like it should work fine for what you are attempting to do. – gmiley Feb 21 '17 at 17:34

1 Answers1

0
<a href="#black">black</a>
<a href="#blue">blue</a>

<script type="text/javascript">
$(window).on('hashchange', function(e){
    var origEvent = e.originalEvent;
    resultdata = origEvent.newURL;
    var black = resultdata.match(/black/);
    if (black){
      console.log(black);
    }
});
</script>
Gnanasekar S
  • 1,490
  • 11
  • 14