I have a simple jQuery code to change the thumbnail of a post by hiding one image and showing the other, when I hover over the div
for the image. The code works for fine when I hover over the div
s labled in the .thumbs
class, but I also want to add a feature so that when I hover over the title the same thing happens and the thumbnails change.
The problem is that if I add the .headline
to the jquery selector I don't get the result I want and the images change when I hover over the thumbnails.
I know why this is happening but don't know how to solve it. Since I only want the image of the post I'm hovering over to change I am using $(this)
, and since the images are both inside .thumbs
there is no problem. But the headline isn't inside the .thumbs
div and therefor when I use $(this).headline
it's like I'm saying thumbs.headline
which doesn't exist. How can I not put the headline inside the same div
and still know which post I'm hovering over?
$('.thumbs').hover(
function() {
console.info('in');
$(this).children('.first').css('display','none');
$(this).children('.second').css('display','block')
},
function() {
console.info('out');
$(this).children('.second').css('display','none');
$(this).children('.first').css('display','block');
});
HTML Code:
<h2 class='headline'><a href="<?php the_permalink() ?>"><?php the_title() ?></a></h2>
<?php if ( has_post_thumbnail() ){ ?>
<a href="<?php the_permalink(); ?>"></a>
<div class='thumbs'>
<div class='first'><?php the_post_thumbnail()?></div>
<div class='second'><?php MultiPostThumbnails::the_post_thumbnail(get_post_type(), 'secondary-image');?></div>
</div>
If wrapping them isn't an option, this should work:
$('.thumbs').each(function () {
var thisThumbAndHeadline = $(this).add($(this).prevAll('.headline:first'));
thisThumbAndHeadline.hover(function () {
console.info('in');
thisThumbAndHeadline.children('.first').hide();
thisThumbAndHeadline.children('.second').show()
},
function () {
console.info('out');
thisThumbAndHeadline.children('.first').show();
thisThumbAndHeadline.children('.second').hide();
}).trigger('mouseout');
})
A simple solution would be to apply the listener to a wrapper that goes around both the title and the thumbs.
<div class="wrap">
<h2 class='headline'> ... </h2>
<div class='thumbs'>
<div class='first'> ... /div>
<div class='second'> ... </div>
</div>
</div>
$('.wrap').hover(
function() {
console.info('in');
$(this).find('.first').css('display','none');
$(this).find('.second').css('display','block')
},
function() {
console.info('out');
$(this).find('.second').css('display','none');
$(this).find('.first').css('display','block');
}
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.