RMD2411
RMD2411

Reputation: 59

Revert to original image after jquery hover better way?

to replace images on hover i have used jquery:

<script  type='text/javascript'>

            $(document).ready(function(){

                var blog1 = $(".blogimage1").attr('src');


                $(".imghover").hover(function() {
                    $(this).attr("src","images/imghover.png");
                        }, function() {
                    $(this).attr("src",blog1);
                });
            });

        </script>

here is the html:

<a href="blog-inner.html" title="read more">
                <img src="images/blogpost4.jpg" alt="blog post title" class="img-responsive imghover blogimage1">   
            </a>

and it works exactly like i want it to, however i dont know how many blog images there will be so for now i would have to add in blogimage1, blogImage2, etc into the html and do the same with jquery. is there a way i can do this without having to store each original blog image and write the same function a million times?

Upvotes: 0

Views: 1242

Answers (2)

Satpal
Satpal

Reputation: 133453

Use .data() to store original image path.

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

code

$(".imghover").hover(function() {
    $(this).data('orgimage', this.src); //Store data
    this.src = "images/imghover.png";
}, function() {
    this.src = $(this).data('orgimage'); //Retrieve and set original image path
});

Upvotes: 1

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28523

Try this : You can save previous image in blog1 variable when mouse hover and replace it back when mouse leave.

$(document).ready(function(){
   var blog1 = '';

  $(".imghover").hover(function() {
       //save previous image in variable
       blog1  = $(this).attr('src');
       $(this).attr("src","images/imghover.png");
     }, function() {
          $(this).attr("src",blog1);
  });
});

Upvotes: 3

Related Questions