views:

29

answers:

1

In an effort to keep code down I was hoping to use regular expressions with jQuery to switch the on and off states inside a hover for an image.

jQuery:

$(function(){
  $("ul.dropdown li").hover(function(){
    $(this).addClass("hover");
    $('ul:first',this).css('visibility', 'visible');

  }, function(){
    $(this).removeClass("hover");
    $('ul:first',this).css('visibility', 'hidden');
  });
});

html:

<ul class="dropdown">
  <li><a href=""><img src="images/nav_first_off.png" /></a>
    <ul class="sub_menu sub1"><li>
      <div class="topnav_dropdown_left"><a href=""><img src="images/topnav_dropdown_first.jpg" /></a></div>
    </li></ul>
  </li>
  <li><a href=""><img src="images/nav_second_off.png" /></a>
    <ul class="sub_menu sub2"><li>
      <div class="topnav_dropdown_left"><a href=""><img src="images/topnav_dropdown_second.jpg" /></a></div>
    </li></ul>
  </li>
  <li><a href=""><img src="images/nav_third_off.png" /></a>
    <ul class="sub_menu sub3"><li>
      <div class="topnav_dropdown_left"><a href=""><img src="images/topnav_dropdown_third.jpg" /></a></div>
    </li></ul>
  </li>
</ul>

So with using the hover function above changing the subsequent nav_first_off.png, nav_second_off.png with the li hover and using the regex to cut the _off.png and switch to _on.png.

Any help would be appreciated, and thanks for even looking.

A: 

You can pass a function into .attr() to change the src attribute, like this:

$(function(){
  $("ul.dropdown li").hover(function(){
    $(this).addClass("hover");});
    $('ul:first',this).css('visibility', 'visible');
    $('a img', this).attr('src', function(i, src) { 
      return src.replace('_off','_on'); 
    });
 }, function(){
    $(this).removeClass("hover");
    $('ul:first',this).css('visibility', 'hidden');
    $('a img', this).attr('src', function(i, src) { 
      return src.replace('_on','_off'); 
    });
  });
});

In the function, the src parameter in function(i, src) is the old src value, so we're just doing a .replace() on that, you can pass it a more complicated regex if needed as well.

Nick Craver
Works like a charm! Thanks I always try not to use regex as for the speed hit, but wasn't sure on that and I was over-thinking the selector.
Chris W
@Chris - Welcome :) Make sure to accept answers on this and future questions via the check-mark beside the one that helped!
Nick Craver