Kim
Kim

Reputation: 43

jquery global var vs local var

trying to teach myself jquery. The following code snippet works fine but I think it is possible to make the code shorter / more efficient.

  //Alter the stylesheet to hide the contents of the page initially. 
  //When the page is loaded, fade in the contents slowly.
  var backgroundBuffer;
  $('p').mouseover(function() {
      backgroundBuffer = $(this).css("background-color");
      $(this).css({"background-color": 'yellow'});
    }).mouseout(function(){
      $(this).css({"background-color": backgroundBuffer});
  });

I do not want to declare "backgroundBuffer" globally because I never use it again. But if I declare it within .mouseover() the system does not recognize it in the later .mouseout()

  //Alter the stylesheet to hide the contents of the page initially. 
  //When the page is loaded, fade in the contents slowly.
  $('p').mouseover(function() {
      var backgroundBuffer; 
      backgroundBuffer = $(this).css("background-color");
      $(this).css({"background-color": 'yellow'});
    }).mouseout(function(){
      $(this).css({"background-color": backgroundBuffer});
  });

thx for your help!

Upvotes: 2

Views: 93

Answers (2)

Evan Borden
Evan Borden

Reputation: 301

This is a situation where the jQuery data method would be helpful. That way you can access that variable from the jQuery object.

 //Alter the stylesheet to hide the contents of the page initially. 
  //When the page is loaded, fade in the contents slowly.
  $('p').mouseover(function() {
      var $this = $(this);
      $this.data('backgroundbuffer', $this.css("background-color")).css({"background-color": 'yellow'});
    }).mouseout(function(){
      var $this = $(this);
      $this.css({"background-color": $this.data('backgroundbuffer')});
  });

Upvotes: 2

Bernie
Bernie

Reputation: 5055

Use jQuery data to store the initial value...

$('p').mouseover(function() {
  $(this).data('oldcolor', $(this).css("background-color")).css('background-color', 'yellow');
}).mouseout(function(){
  $(this).css("background-color",$(this).data('oldcolor'));
});

Upvotes: 3

Related Questions