henri
henri

Reputation: 21

Jquery: how can I store a variable inside a function, and use it outside?

I am trying to change a text according to a mouse hover event:

$(document).ready(function() { 
    $('.blog_post_container').hover(function() {
        var title = $(this).find('.blog_title').text();  
        $(this).find('.blog_title').text("READ MORE >");
    }, function() {
        $(this).find('.blog_title').text(title);
    }
});

In the HTML: div.blog_title is inside div.blog_post_container.

The variable "title" was created inside the function called on mouse hover to store the blog title of that specific blog post. The idea was to use it later, when the mouse leaves the blog_post_container, but I cannot use it outside the function where it was created.

I cannot either create the variable before that function, because it will always return the title of the first blog post.

I know the solution is simple, but I'm just not finding it. Any help is appreciated!

Upvotes: 2

Views: 63

Answers (3)

Federico
Federico

Reputation: 3920

Maybe an overly complicated solution:

function rollOver(oElem, tHoverText){
  this.tHover=tHoverText;
  this.oElem=oElem;
  this.init()
};

rollOver.prototype.init = function() {
  this.oTitle = this.oElem.querySelector('.blog_title');
  this.tTitle = this.oTitle.innerHTML;
  this.initEvents();
};

rollOver.prototype.initEvents = function() {
  var self = this;
  this.oTitle.addEventListener('mousehover', this.changeTitle.bind(this), false);
  this.oTitle.addEventListener('mouseout', this.restoreTitle.bind(this), false);
};

rollover.prototype.changeTitle = function() {
    var self = this;
    this.oTitle.innerHTML = self.tHover;
};

rollover.prototype.restoreTitle = function() {
    var self = this;
    this.oTitle.innerHTML = self.tTitle;
};

You can use it like this:

var blogPost = document.getElementsByClassName('blog_post_container')[0];

var b = new rollOver(blogPost, "Read more");

To retrieve the title text, use b.tTitle.

Upvotes: 0

Paul
Paul

Reputation: 20061

Store the title like this:

$(this).data('blog-title', title);

You can then retrieve it later with just a reference to the element:

var title = $('.blog_post_container').data('blog-title');

.data() API

Upvotes: 2

Marcos Pérez Gude
Marcos Pérez Gude

Reputation: 22158

Remove var to attach variable to window object

   title = $(this).find('.blog_title').text();  

It's better if you define it before the document ready

   var title;
   //document ready code

Upvotes: 0

Related Questions