I have a grid that contains two rows and three columns. Each column has a picture, a title, and a subtitle. All the pictures have the same class, let's say "image".I want the picture to change during hover. I have a div with the other image (the one that I want to show on hover) with the property display: none;
This is the HTML code:
<div class="row-1">
<div class="col-1">
<div class="view-field-image">
<div class="field-content">
<img class="image" src="../.." al="">
</div>
</div>
<div class="view-field-collapsed">
<div class="field-content">
<img class="collapsed" src="../.." al="">
</div>
</div>
</div>
<div class="col-2">
</div>
<div class="col-3">
</div>
</div>
This is the js code:
(function ($, Drupal) {
'use strict';
Drupal.behaviors.hoverEffect = {
attach: function (context, settings) {
$('.view-field-image .field-content', context)
.once()
.each( function () {
$(this, context)
.mouseenter( function () {
console.log('enter');
$('image', context).css('display', 'none');
$('.collapsed', context).css('display', 'block');
})
.mouseleave( function () {
console.log('leave');
$('image', context).css('display', 'block');
$('.collapsed', context).css('display', 'none');
});
});
}
};
})(jQuery, Drupal);
I don't have the excepted result. When I hover over the picture all the pictures show the hidden picture with the collapsed class. Furthermore the picture with the class= "image" doesn't disappear.
After playing around with the javascript for a while, I realised you could simple do this with CSS, no Javascript needed.
You will just have to add a class to the columns, in the case of this example it is
image-col
.After posting this I saw that the problem is probably more than the way the context variable is being used.
But I am leaving the answer here on request of the OP.
Original (wrong) answer
You are using the context variable wrong.
context will be what jquery looks into to find an element.
eg.
$('.something', context)
jquery will search for ".something" inside of context.
Your code uses:
$('image', context).css('display', 'none');
but, as this is in a loop, you really only want the context to be the current element in the loop.So your each loop should loop more like: