Reputation: 77
How can I write this two (or more) same functions in one - to compress JS data - they are same functions but different css. It is for highlighting different imgs on hover specific li - one li for one img
$(".class1").mouseenter(function () {
$(".class2").addClass("highlight");
});
$(".class3").mouseenter(function () {
$(".class4").addClass("highlight");
});
Upvotes: 1
Views: 94
Reputation: 87203
data-*
attribute to store the selector of the element on which the class highlight
is to be added.data
attribute to perform actions on itJavascript:
$('.myClass').mouseenter(function() {
$($(this).data('target')).addClass('highlight');
});
And in HTML, add data-target
attribute.
<div data-target=".class2" class="class1 myClass">Lorem</div>
<!-- ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^ -->
<div data-target=".class3" class="class2 myClass">Ipsum</div>
Upvotes: 4
Reputation: 29683
Following @Tushar's answer with a single line you can add multiple class
with a ,
separated values as below:
Add a data-*
(*->Any value) say to
to your elements like one below:
<div data-to=".class2" class="class1">First Class</div>
<div data-to=".class3" class="class2">Second Class</div>
Then with JS:
$(".class1,.class2").mouseenter(function(){
$($(this).data('to')).addClass("highlight");
});
Upvotes: 2
Reputation: 4616
You could use something like the following, but i would advise you to rethink your css (class) - structure as @Tushar suggested!
[['.class1', '.class2'], ['.class3', '.class4']].forEach(function(value) {
$(value[0]).mouseenter(function(event) {
$(value[1]).addClass("highlight");
});
});
Upvotes: 3