Improving jquery code

2

I have a code in jquery that does the following, it creates a class after the hover, until it is working normally, but since I will have to replicate this action in other places but will change the css properties of each section, in the case are four, but I did not want to have to keep replicating the same code several times, does anyone know a way to improve this code so it does not get repetitive?

$('.bg_hover').hover(
function(){
    $(this).addClass('ativo');
},
function(){
    $(this).removeClass('ativo');
}
);

$('.bg_hover_dois').hover(
function(){
    $(this).addClass('ativo_dois');
},
function(){
    $(this).removeClass('ativo_dois');
}
);
    
asked by anonymous 08.10.2018 / 16:14

3 answers

0

Adds a unique ID to each of its elements, and in that function you get that id and add the class and remove it, depending on its ID.

And all the elements you want to have this behavior must have the class bg_hover , only bg_hover

$('.bg_hover').hover(
function(){
    var id = $(this).attr("id");
    $(this).addClass('ativo'+ id);
},
function(){
    var id = $(this).attr("id");
    $(this).removeClass('ativo' + id);
}
);

So you do not have to keep replicating, just change the id of each element you want to have this behavior

    
08.10.2018 / 16:19
0

Make a função you receive as a parameter:

1- O elemento to be modified.

2 - The elemento class.

It would look like this:

function ModificaElemento(element, classe) {
  $(element).hover(
    function(){
        $(element).addClass(classe);
    },
    function(){
        $(element).removeClass(classe);
    }
  );
}

ModificaElemento(".bg_hover", 'ativo');
ModificaElemento(".bg_hover_dois", 'ativo');
.ativo {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="bg_hover"> Ativo  </div> <br>
<div class="bg_hover_dois"> Ativo 2 </div>

The function call: ModificaElemento(elemento, classe)

    
08.10.2018 / 16:24
-1

You would not need Javascript for this, you can only solve with HTML and CSS:

HTML

<a href="#" class="active">meu link</a>
<a href="#" class="active2">meu link 2</a>

CSS

.active:hover {
    text-decoration: none;
}

.active2:hover {
    color: yellow
}

But if you need or want to use javascript and jQuery you can use toggleClass link

It would look something like this:

HTML

<a href="#" data-class="active" class="link-hover">meu link</a>
<a href="#" data-class="active2" class="link-hover">meu link 2</a>

JAVASCRIPT

$(".link-hover").hover(function(){
      $(this).toggleClass($(this).data('class'));
});

CSS

.active {
    text-decoration: none;
}

.active2 {
    color: yellow
}

Then the classes you can set up as you need, and only change the attribute data-class

    
08.10.2018 / 16:19