code_junkie

jQuery rollovers using multiple ids and classes

Nov 13th, 2011
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. <img src='' class='apple fruit red' />
  2.  
  3. $(".apple").mouseover(function() {
  4. $(".apple").addClass("overState");
  5. });
  6.  
  7. <img src="the-big-red-apple.jpg" class="tagged tag-big tag-red tag-apple" />
  8.  
  9. $('img.tagged')
  10. .each(function() {
  11. var thisClasses = this.className.split(/s+/); // array of classes.
  12. var search = [];
  13. for (var i = 0; i < thisClasses.length; ++i) {
  14. if (thisClasses[i].substr(0, 4) == "tag-") {
  15. search.push("." + thisClasses[i]);
  16. }
  17. }
  18. $(this).data("tags", search.join(",")); // ".tag-big,.tag-red,.tag-apple"
  19. })
  20. .hover(function() {
  21. $('img.tagged')
  22. .filter(this.data('tags'))
  23. .addClass("highlight")
  24. ;
  25. }, function() {
  26. $('img.tagged')
  27. .filter(this.data('tags'))
  28. .removeClass("highlight")
  29. ;
  30. })
  31. ;
  32.  
  33. function swapImageGroup(imgSelector,suffix){
  34. if (suffix == null) {suffix = "-hover";}
  35. //imgSelector is the jQuery selector to use
  36. //both imgSelector and suffix must be strings
  37. $(selector).hover(
  38. function() {
  39. $(selector).each(function(){
  40. //store ".jpg" or ".png" or whatever as fileExtension
  41. var fileExtension = $(this).attr("src").substr($(this).attr("src").lastIndexOf("."));
  42. //replace something like ".jpg" with something like "-hover.jpg",
  43. //assuming suffix == "-hover"
  44. $(this).attr("src", $(this).attr("src").replace(fileExtension, suffix + fileExtension));
  45. });
  46. },
  47. function() {
  48. $(selector).each(function(){
  49. //chop off the end of the filename, starting at "-hover" (or whatever)
  50. //and put the original extension back on
  51. $(this).attr("src", $(this).attr("src").split(suffix + ".").join("."));
  52. });
  53. }
  54. );
  55. }
  56.  
  57. swapImageGroup("img.apple");
  58.  
  59. swapImageGroup("img.foo","-active");
  60.  
  61. a.apple:hover img {
  62. /* whatever you want to change here */
  63. }
Add Comment
Please, Sign In to add comment