0

I'm writing a code currently, and it's working good so far, however, my "onmouseout" command doesnt work properly. Ill give you the .js first:

function getEventTarget(e){
    e = e || window.event;
    return e.target || e.srcElement;
}   

var ul = document.getElementById('index_cards');
ul.onclick = function (event) {
    var target = getEventTarget(event);
    if(target.tagName != 'LI')
    target = target.parentNode;
    if(hasClass(target, 'active'))
        target.className='';
    else
        target.className='active';
}
ul.onmouseout = function (event){
    var target = getEventTarget(event);
    if(target.tagName != 'LI')
    target = target.parentNode;
    if(hasClass(target, 'active'))
            target.className='';
}

function hasClass(el, className){
    return new RegExp(className). test(el.className);   
}

So this is what happens: When I leave the li element, the effect works, but same goes for inside the element. If I move outside of a tag inside the html element(move out of <p> or out of <img>) the effect applies as well. I only want to apply the onmouseout to the li element though. What am I doing wrong?

Edit: Code works now, the solution was like this:

    function getEventTarget(e){
    e = e || window.event;
    return e.target || e.srcElement;
}

function onMouseOut(event) {
        e = event.toElement || event.relatedTarget;
    if (e.parentNode == this || 
                           e == this) {
      return;
    }
    var target = getEventTarget(event);
    if(target.tagName != 'LI')
    target = target.parentNode;
    if(hasClass(target, 'active'))
            target.className='';
};

var ul = document.getElementById('index_cards');

ul.addEventListener('click', function(event){

    var target = getEventTarget(event);
    if(target.tagName != 'LI')
    target = target.parentNode;
    if(hasClass(target, 'active'))
        target.className='';
    else
        target.className='active';

    target.addEventListener('mouseout', onMouseOut, true);
});

function hasClass(el, className){
    return new RegExp(className). test(el.className);   
}
Frederik Witte
  • 1,167
  • 2
  • 11
  • 35

1 Answers1

0

Try e.currentTarget instead of e.target.

Jonathan Lerner
  • 450
  • 1
  • 4
  • 11
  • Hey, thank you for your reply, if you mean to add it at the getEventTarget function, then it sadly doesnt work :/. Then the onclick parameter doesnt even work anymore – Frederik Witte Aug 07 '14 at 14:39
  • Can you create http://jsfiddle.net or something similar to fully illustrate the problem? Or at least include full HTML+JS sample code? – Jonathan Lerner Aug 07 '14 at 14:40