treehouse : what would you like to learn today?
Web Design Web Development iOS Development

JQuery doesn't work in Firefox or IE

  • Hey Everyone!

    This piece of code swops between 2 background images. It currently works in Google Chrome and Safari, but not Firefox or IE. I am a noob with JQuery (this is my first time using it :D) so please help.

    Also it would be nice if I could swop between images by only pressing 1 button, not 2 separate ones like now. But I really for now just want it working in all browsers :)

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
    <html xmlns="http://www.w3.org/1999/xhtml"&gt;
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="css/style.css"/>
    <script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
    $(window).keypress(function(e) {
    if(e.keyCode == 49) {
    $("#image").css("background-image", "url('images/Bloukrans.jpg')");
    }
    });
    $(window).keypress(function(e) {
    if(e.keyCode == 50) {
    $("#image").css("background-image", "url('images/Supertubes.jpg')");
    }
    });
    });
    </script>
    <title>Escape Button</title>
    </head>

    <body>
    <div id="image">
    </div>
    </body>
    </html>


    Thank You!
  • Hi JediN1nja

    This should work across all browsers.


    $(document).ready(function(){
    // image array
    var imgs = ["banner1.jpg", "banner2.jpg"];
    // set init image
    $("#image").css("background-image", "url('images/" + imgs[0] + "')");
    $("#image").attr("rel", 0);
    // handle user key press
    $(this).keypress(function (e) {
    var keynum = "";
    if (window.event) {
    keynum = e.keyCode;
    } else if (e.which) {
    keynum = e.which;
    }
    // if the enter key has been pressed
    if (keynum == 13) {
    // display next image in array or start from the beginning
    var current = $("#image").attr("rel");
    if (current == (imgs.length - 1)) {
    current = 0;
    } else {
    current++;
    }
    // change image
    $("#image").css("background-image", "url('images/" + imgs[current] + "')");
    $("#image").attr("rel", current);
    }
    });
    });