tags:

views:

35

answers:

2

Hi folks. Gotten a lot of great help here! The code here has been helped along by a few folks. Hopefully someone can help me take it to the next level.

Basically, I have code which will add a checkmark after a given period of time to a clicked item in the left navigation. There are going to be other links on the page which are going to trigger the same behavior for the corresponding left links. So for example there would be 10 links on the left, and 10 links on top that would each need to trigger a corresponding link on the left. I am trying to abstract this code so that I can activate it from a different source. To make it easier, it can be thought of as how to trigger this piece of code from a source outside of the navigation. Here's the code:

$(function() {

var thetimeout=null;
 $('#leftnav li a').click(function() {
      $('#leftnav li').not('this').css('background-position','left bottom');
      $(this).parent().css('background-position','left top');
      if(thetimeout!=null) {
          window.clearTimeout(thetimeout);
      }

       thetimeout=window.setTimeout($.proxy(function() {
                 $(this).parent().css('background-image','url(images/check.png)');
            }, this)
      ,5000);
 });

});

I have a working demo (with the top links not working) up here.

Thanks for your time, I really appreciate it.

A: 

maybe this will work?

wireClickEvent("#leftnav li");
wireClickEvent("#topnav li");

function wireClickEvent(selector) {
    $(selector + ' a').click(function() {
        $(selector).not('this').css('background-position','left bottom');
        // rest of your code
        // ...
    }
}
house9
+1  A: 

This is what makes jQuery plugins so nice. Turn your code into a plugin.

Looking at your source, I see the top links are not inside a list. By putting them into a list we can target them the same way.

$('.nav-items,.top-items').checkMyLinks();

Since we're targeting the list, we can perform our plugin logic onto its child items.

$.fn.checkMyLinks=function(opt){
  return this.each(function(){
    var t=$(this),
      timer=null;// each plugin instance has its own timer

    t.delegate('click', 'li a', function(e){
      var parent=$(this).parent();//the <li> above the clicked link

      //css classes here?
      t.find('li').css({backgroundPosition: 'left bottom'});
      parent.css({backgroundPosition: 'left top'})

      //deal with your timer...
    });
  });
};

If you don't want to put the top links into a list, you could modify the plugin to suit.

Good Luck!

czarchaic