I’m using a plugin to store two thumbnails for each post and I’ve created two div’s for each post thumbnail and hidden the second one with it’s css display property set to ‘none’ inside the loop.
<div class='first'><?php the_post_thumbnail()?></div>
<div class='second'><?php MultiPostThumbnails::the_post_thumbnail(get_post_type(), 'secondary-image');?></div>
Using java script when I hover over each post I want to show the second div and hide the first one but the code I’ve written changes all the display properties wile I hover over any of the thumbnails.
How can I know which post the cursor is hovering over and change the thumbnail display property for that post only?
function() {
console.info('in');
$('.first').css('display','none');
$('.second').css('display','block');
},
function() {
$('.second').css('display','none');
$('.first').css('display','block');
//$(this).children("img").fadeTo(200, 1).end().children(".hover").hide();
});
The JavaScript and JQuery
this
keyword is what you are looking for.What is the
this
keyword?this
points to the object that called your function. It sounds confusing at first but looking at a few simple examples clarifies any confusion. For example, in your case, you need to know whatdiv
is being hovered over. What your doing now is writing an individual event for each object and it works in some cases, but obviously runs into multiple problems.The first is what your question is. How can you tell which one is being hovered over? But there is another problem you could run into. What if you had 50
divs
that all needed the same event? It would be both time consuming and space consuming to write 50 lines of CSS display changes. What if there was a way to reduce those 50 lines to one single line?So what does
this
do? Say your HTML markup looked like this:And you want to apply a CSS property to any of the
div
s that are hovered over. The above JQuery says:Or in other words, change
this
div that is currently being hovered over.Obviously, this idea (pun intended) can be used in many ways to significantly shorten JavaScript programming. If you want to look more into the documentation of
this
, there’s plenty of good sources out there. Here are a few:http://www.quirksmode.org/js/this.html
http://learn.jquery.com/javascript-101/this-keyword/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
It took awhile for me to grasp, but definitely improved my JS programming once I did. Also important to note:
$(this)
only works in JQuery, in JavaScript it is simplythis
. Obviously, you can use the simpler version,this
, in JQuery as well.One last thing, I made a quick demo for you to see a live implementation of the
this
keyword.I hope this answer was helpful for you 😉