0

I want to remove the clicked element from the page after a certain amount of time (1.5 seconds). Here is the code (including some background info):

function AttachEvent(element, type, handler) {
    if (element.addEventListener) {
        element.addEventListener(type, handler, false);
    } else if (element.attachEvent) {
        element.attachEvent('on' + type, handler)
    } else {
        element['on' + type] = handler;
    }
}

AttachEvent(window, "load", function() {

    AttachEvent(mydiv, "click", do_stuff); 
});

function do_stuff(e){
    e = e || window.event;
    var target = e.target || e.srcElement;  

    //some stuff        

    //remove object
    setTimeout('target.parentNode.removeChild(element);', 1500);
}

Internet Explorer complains about target being undefined in the anonymous function. How do I set this timeout in Internet Explorer?

2
  • What is element in setTimeout('target.parentNode.removeChild(element);', 1500);? Commented Mar 16, 2012 at 20:22
  • I don't know. I must have overlooked that when I initially inserted the code into my script. Commented Mar 16, 2012 at 20:41

1 Answer 1

2

Don't use a string for setTimeout. Just don't. Instead pass an anonymous function (demo):

function do_stuff(e){
    e = e || window.event;
    var target = e.target || e.srcElement;  

    //some stuff        

    //remove object
    setTimeout(function(){target.parentNode.removeChild(target);}, 1500);
}

If you use the function above, the current value of target will be used inside of the anonymous function. If you pass a string, your browser looks for a global object named target, which will fail, since target a function scope variable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.