1

I'm working on the js/JQuery project on The Odin Project with a partner, and we've hit a wall with the very last task, which is to increase the opacity of the squares as the mouse reenters them. We got stuck while trying to achieve this via two css classes, and creating mouseenter events for each.

Essentially, we want to start with all of the squares being the grey class, and after entering them for the first time, assigning them the fiftyshades class. When subsequently entering them, we want the event handler for the fiftyshades class to increase the opacity.

However, once the element has both classes, it never enters the mouseenter function for fiftyshades, only for grey. We've already worked around it by putting the opacity logic inside the grey.mouseenter, but according to this answer, I would think that our original approach should work. That says that both handlers should be called, but debugging I can clearly see that fiftyshades.mouseenter is never entered.

This is where we stand after much fiddling with the relevant javascript for this functionality:

$("#fiftyshades").click(function() {
reset();

$(".grey").mouseenter(function(){
    if (!$(this).hasClass("fiftyshades"))
    {
        $(this).addClass("fiftyshades");
        console.log("Adding fiftyshades")
        if ($(this).hasClass("fiftyshades"))
        {
            console.log("Add was success");
            console.log("Classes: ")
            var className = $(this).attr('class');
            console.log("     " + className);
        }
    }
});

$(".fiftyshades").mouseenter(function(){
    var shade =  parseFloat($(this).css("opacity"));
    console.log("Shade: " + shade);
    if (shade < 1) {
        $(this).css("opacity", shade + 0.1);
    }
});
});

Here's a fiddle with the full project. Enter some number to start with, then hit Reset fifty shades to access this functionality.

Community
  • 1
  • 1
Fulluphigh
  • 504
  • 1
  • 7
  • 19

1 Answers1

1

Much simpler solution is something like this

$(".grey").mouseenter(function(){
  var opacity = $(this).data('opacity') || 0;
  $(this).css("opacity", opacity = (parseInt(opacity) == 1 ? opacity : opacity + 0.1));
  $(this).data('opacity', opacity);      
});

But to your actual issue

you are assigning handler before the element actually exists in the DOM, what you should be doing is event delegation

$(".container").on('mouseenter', ".fiftyshades", function (e) {
    var shade = parseFloat($(this).css("opacity"));
    console.log("Shade: " + shade);
    if (shade < 1) {
        $(this).css("opacity", shade + 0.1);
    }
});

See updated fiddle

Community
  • 1
  • 1
code-jaff
  • 8,472
  • 4
  • 30
  • 52
  • Great, thank you! Yeah, like I said, we realized the smarter solution, but I was bothered by why this didn't work. That explains it though. – Fulluphigh Mar 16 '15 at 13:02