Rudi
Rudi

Reputation: 77

How to write many functions in one JS function

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

Answers (3)

Tushar
Tushar

Reputation: 87203

  1. Add a common class to all the elements of interest and then bind event on the common class.
  2. Use data-* attribute to store the selector of the element on which the class highlight is to be added.
  3. Use the selector on data attribute to perform actions on it

Javascript:

$('.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

Guruprasad J Rao
Guruprasad J Rao

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

Tobias Golbs
Tobias Golbs

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

Related Questions