Call a function on an anchored object


/ Published in: jQuery
Save to your folder(s)

Sometimes you click a link like faq.html#item5 and, after the browser jumps you to the anchor, you have trouble spotting the item you're looking for. anchorAway is a little function that helps you call a function on anchored items, maybe something like a scrollTo or a background color, that helps users easily spot the content you directed them to.

anchorAway parses the window.location for an anchor (#foo), finds it, and calls the function (act(bar)) on it. It also finds any on-page links to the objects you've specified and binds the same function to their click event.


Copy this code and paste it in your HTML
  1. $.fn.anchorAway = function(act){
  2. urlArr = window.location.href.split("#");
  3. anchorName = urlArr[(urlArr.length - 1)];
  4. $(this).each(function(){
  5. targetId = $(this).attr("id");
  6. bindIt = function(i){
  7. $("a[href='#" + i + "']").each(function(){
  8. $(this).bind('click', function(){
  9. act($("#" + i));
  10. });
  11. });
  12. }
  13. bindIt(targetId);
  14. if (targetId == anchorName) {
  15. act($(this));
  16. }
  17. });
  18. }
  19.  
  20.  
  21. === USAGE ===
  22.  
  23. $("div").anchorAway(function(obj){
  24. obj.css("background-color","yellow");
  25. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.