I have an on
function that has two mouse events inside of it mouseenter
and mouseleave
. When these events are triggered they run different functions, one adds a class, the other removes it.
$(this).siblings('.testimonial').find('p').addClass('unseen');
$(this).siblings('.testimonial').find('p').removeClass('unseen');
The thing is, I’m doing the following DOM traversal twice:
$(this).siblings('.testimonial').find('p')
But I don’t see how I can save this traversal as a variable in one function and use it as another. Here is my full JS code:
JavaScript
(function ($) {
var testimonial = $('.testimonial');
var testimonialHeight = testimonial.outerHeight();
var testimonialWidth = testimonial.outerWidth();
testimonial.find('p').addClass('unseen');
testimonial.css({
height: testimonialHeight,
width: testimonialWidth
});
$('.client').on({
mouseenter: function() {
$(this).siblings('.testimonial').find('p').removeClass('unseen');
},
mouseleave: function() {
$(this).siblings('.testimonial').find('p').addClass('unseen');
}
});
})(jQuery);
HTML
<ul class="list-unstyled list-inline">
<li>
<div class="testimonial"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.<p></div>
<img class="client" src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/128.jpg" alt="" />
</li>
<li>
<div class="testimonial"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p></div>
<img class="client" src="https://s3.amazonaws.com/uifaces/faces/twitter/gerrenlamson/128.jpg" alt="" />
</li>
<li>
<div class="testimonial"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p></div>
<img class="client" src="https://s3.amazonaws.com/uifaces/faces/twitter/jadlimcaco/128.jpg" alt="" />
</li>
</ul>
Can anybody suggest a better way of doing this?
Thanks.