Subpar Web Dev Subpar Web Dev - 7 months ago 11
Javascript Question

Why is Internet Explorer not liking my click event?

This is the strangest thing ever. I have

<div class="button-holder">
<button id="video-play">Play Interactive Video</button>
<script type="text/javascript">
$(function () {
$('#video-play').click(function(){
var id = "ssvid", src = "assets/Cisco_SmartStack_Interactive_04192016.mp4", type = "video/mp4";
var source = document.createElement('source');
source.src = src;
source.type = type;
var video = document.getElementById(id);
video.appendChild(source);
window.VidHandler = new VideoHandler(id, src, type);
VidHandler.PlayFromBeginning();
$(this).remove();
});
});
</script>
</div>


and everything is going fine on FF and Chrome, but in IE, the first time it is clicked, I get


InvalidStateError


and the element doesn't get removed and the events inside the
VideoHandler
function don't fire correctly. After pushing it again it works as intended.

Answer

Hmm, it is probably because you are adding elements to the document and then attempting to interact with them before they get added. I believe I've seen Firefox and Chrome act as if they're working with more than one thread in instances like this while IE will work through everything in your click handler before updating the DOM.

Try adding the elements and the then put your actions to interact with those elements inside a setTimout function, like so:

$('#video-play').click(function(){
         var id = "ssvid", src = "assets/Cisco_SmartStack_Interactive_04192016.mp4", type = "video/mp4";
         var source = document.createElement('source');
         source.src = src;
         source.type = type;
         var video = document.getElementById(id);
         video.appendChild(source);
         setTimeout(function(){ 
            window.VidHandler = new VideoHandler(id, src, type);
            VidHandler.PlayFromBeginning();
            $(this).remove();
         }, 100);
 });

Doing this will give your DOM a fraction of a second to update.