0

I wrote the following code to change mouseover images:

<script language="Javascript">
<!--
function ShowPicture(id) {

var css = '.test1 a:hover:after{content: url(_images/recurring/'+id+'); }';
style = document.createElement('style');

if (style.styleSheet) {
    style.styleSheet.cssText = css;
} else {
    style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
}
</script>

It works perfectly on Chrome, but once IE8 hits this script, it stop the entire page in it's tracks. What is the best way of handling this? is there some equivalent to : if(internetexplorer8 == true) command? or is the script itself flawed, but chrome allows it to run anyways?

user2067101
  • 103
  • 7

1 Answers1

0

There is a known bug related to createTextNode with IE 8. IE 8 and 7 bug when dynamically adding a stylesheet

Since you are already using Javascript, there is no advantage in increasing the complexity by bringing CSS into the mix.

You can essentially loop through all of the images, store the original source as a data attribute on the image and attach listeners to the image that swap between it and the roll over.

The code below should work with some modifications.

window.addEventListener('load', function(e) {
    //preload image to prevent flicker

    var imgs = document.getElementsByTagName('img');
    //loop 

    for (var i = 0; i < imgs.length; i++) {
        //add your code here to determing rollover original/replacement binding, my example is hard coded
        var rolloverSrc = 'https://farm3.staticflickr.com/2852/9704174376_b5c406c710_q.jpg';
        //preloading img into memory
        var preloadImg = document.createElement('img');
        preloadImg.src = rolloverSrc;
        //Alias varaible to keep in scope for listeners
        var img = imgs[i];

        preloadImg.addEventListener('load', function(e) {
            //Attach rollover events after image preloads
            img.addEventListener('mouseover', function(e) {
                this.setAttribute('data-orginal-src', this.src);
                this.src = rolloverSrc;

            }, false);

            img.addEventListener('mouseout', function(e) {
                var original = this.getAttribute('data-orginal-src');
                this.src = original;

            }, false);
        }, false);

    }
}, false);

You can see it here:https://jsbin.com/juladaq/edit?js,console,output

Community
  • 1
  • 1
Ron Sims II
  • 566
  • 5
  • 10