开发者

Take action based on fragment ID in jQuery

I have a CSS modal box on my site that is opened by clicking on an anchor which looks like this:

<a href="#modal-box">Click here to open modal box</a>

Once users have clicked that, the modal box opens up, and they find themselves at: http://example.com/#modal-box

This, to me,开发者_如何学Python represents a location on my site, so I would like for users to be able to copy and paste that url into another browser, and get the same modal box popped up.

Using jquery, is there a way to capture the fragment ID that a user is at, and to then to take an action based on that?


If you want to do it right (i.e. back button support) then you'll want to trap the hashchange event and act on that, this event is fired by modern browsers when the URL fragment changes. However, not all browsers support hashchange so you'd have to work around that. You're better off using a pre-built solution such as:

  • Ben Alman's hashchange plugin.
  • Sammy.js
  • jQuery BBQ

The basic hashchange plugin is probably your best bet unless you're building a JavaScript application with complicated routing and argument handling.

You could look at location.hash all the time too. But, then you'd have to find the corresponding link and simulate a click on it to get the browser to behave. Once you start doing that sort of thing you're probably better off with one of the above plugins/frameworks and some sort of formal routing system.


You probably could do that with jQuery, but you can also just use a native JavaScript property: location.hash gives you #modal-box.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜