The class is not built into the DOM (JQuery)

3

Next code:

<script>
$(document).ready(function() {
$("#inicio").hover(function() {
$("#inicio").addClass("fogo");
$("#inicio").removeClass("fogo");
});


});
</script>

And the HTML:

<li><a id="inicio">Inicio</a></li>

In class * (.fire) *, I inserted these CSS codes, basically it displays a gif and positions it.

<style>
.fogo {
background-image: url("http://www.bestgraph.com/gifs/paysages/flammes/flammes-10.gif");
background-position: 0px center;
}
</style>

Forget stylization, I took the css out to make it easier to see the code. I tested here, and by hovering over "a", it gets a class, empty, getting something like:

<li><a id="inicio" class="">Inicio</a></li>

What do I do to simply put the .fire class in the element, and when I quit the mouse pull it out? For me basically using hover, and two functions, the first for mouse input on the element, and another working on the output .. Thanks!

    
asked by anonymous 31.12.2014 / 21:59

2 answers

4

You are adding the class and then removing it.

In the DOM notes that the class attribute is added but empty because jQuery adds the class to the element where for the effect it applies the class attribute but shortly after you remove the element class, jQuery removes the class but leaves the class empty attribute.

Your initial HTML:

<li><a id="inicio">Inicio</a></li>

After using the .addClass() method:

<li><a id="inicio" class="fogo">Inicio</a></li>

After using the .removeClass() method:

<li><a id="inicio" class="">Inicio</a></li>

Solution

It seems to me that you want to add the class when the mouse is over the element and remove when the mouse is no longer on the element, so you can change your code to the following:

$( "#inicio" )
  .mouseenter(function() {
    $("#inicio").addClass("fogo");    
  })
  .mouseleave(function() {
    $("#inicio").removeClass("fogo");    
  });

So we delegate two events in the target element, the .mouseenter() to trigger an action when the mouse goes over the element , and .mouseleave() for when the mouse is no longer on top of the element.

    
31.12.2014 / 22:37
4

Live! Your problem is in using the wrong events. You should use the mouseover and mouseout

Look at an example that works:

$(document).ready(function(){

    //evento quando o rato fica sob o elemento #inicio
    $("#inicio").mouseover(
      function(){
       $("#inicio").addClass("fogo");
      });
    //evento quando o rato sai sobre o elemento #inicio
    $("#inicio").mouseout(
        function(){
            $("#inicio").removeClass("fogo");
        });
});

My test link in jsfiddle: link Hope it helps.

    
31.12.2014 / 22:38