Pregunta

I put together a simple fiddle to try to work out what I am trying to do. Basically I have an editor that the user can manipulate different elements on. When the user hover over an element that is editable a checkered outline appears via css. Once the user clicks the outline changes to a solid outline to indicate that this is the element that is now editable so I remove the hover event on the click so no if they move the mouse around the page not checkered lines appear around the other editable elements on the page, essentially locking them except for the one that is selected.

If the user decides not to edit that element I have a button that allows them to go back and"cancel" which reenables should hover for all the editable elements. So far I have been unable to get the event enabled again once I have it in a locked state.

Here is a fiddle http://jsfiddle.net/ZqfTX/276/

$('.element').on({
    mouseover: function(){
        $(this).css({'outline':'2px dashed red'});
    },
     mouseleave: function(){
        $(this).css({background: '#CCC'});
    },
    click: function(){
        $(this).off('mouseover');
        $(this).off('mouseleave');
        $(this).css({'outline':'2px solid #369fe4'});
    }
});

$('#button').click(function(){
      $('.element').on('mouseover');
      $('.element').on('mouseleave');

});

Can someone please take a look and let me know why I am unable to reenable the event using .on

¿Fue útil?

Solución

You need to reset the function you want to fire on("mouseover")

function setHover(){
    $('.element')
        .css({'outline':'none'})
        .off('mouseover mouseleave click')
        .on({
            mouseover: function(){
                $(this).css({'outline':'2px dashed red'});
            },
             mouseleave: function(){
                 $(this).css({'outline':'none', background: '#CCC'});
            },
            click: function(){
                $('.element').off('mouseover mouseleave click');
                $(this).css({'outline':'2px solid #369fe4'});
            }
        });
}

$('#button').click(function(){
   setHover();
});

setHover();

Otros consejos

HTML:

<div class="element inactive"></div>
<br>
<div id="button"><a href="#">Cancel Editing</a></div>

JS:

$(document).on({
    mouseleave: function(){
        $(this).css({background: '#CCC'});
    },
    click: function(){
        $(this).toggleClass('inactive active');
    }
}, '.element.inactive');

$('#button').on('click',function(){
      $('.element.active').toggleClass('inactive active');    
});

CSS:

.element{
    position:absolute;
    top:60px;
    left:100px;
    background: #ccc;
    width: 200px;
    height: 120px;
}
.element.inactive:hover {
    outline: 2px dashed red;
}
.element.active {
    outline: 2px solid #369f34;
}

FIDDLE

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top