Dan Sorensen
Dan Sorensen

Reputation: 11753

Why can't I bind to a click event from a css class in IE 7-8?

Why doesn't this JavaScript work in Internet Explorer 7-8? All I am trying to do is wire up the 'click' event for multiple DIVs by using jQuery to select the DIVs by class name.

It works in Firefox, Chrome, Safari. In IE, it will only work in Browser Mode: IE 9 / Document Mode: IE 9 standards". Can't get it to work in IE 7 or 8.

<!DOCTYPE html>
<head>
    <title>IE Click Target Test</title>
</head>
<body>

    <div class="ClickTarget">Button 1</div>
    <div class="ClickTarget">Button 2</div>

    <!-- load jQuery 1.6.4 from CDN -->
    <script type="application/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

    <script type="application/javascript">
        // This works fine in all browsers except IE pre-9. 
        $(document).ready(function () {

          $(".ClickTarget").click(function () {
              alert("If you can see me, it worked!");
          });

        });
    </script>
</body>
</html>

For some reason, maybe the impending holiday, I'm overlooking something. Any ideas why I can't register the click in IE?

Upvotes: 0

Views: 366

Answers (4)

Chris
Chris

Reputation: 3162

As Shankar said originally, it's your script type not being "text/javascript"

I tried this JSFiddle in IE8 and worked fine for me.

http://jsfiddle.net/Nna2T/

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69915

Try changing script tag's type attribute to text/javascript it should work fine in all the browsers.

Upvotes: 2

asawyer
asawyer

Reputation: 17808

This is not an answer but comments can't format code, so just an FYI...

This:

$(document).ready(function () { 
    ...
});

Can be shorted to just:

$(function() { 
    ...
});

Upvotes: 0

ipr101
ipr101

Reputation: 24236

I think it's the type="application/javascript" in your <script> tags -

"text/javascript" is the only type that is supported by all three browsers. However, you don't actually need to put a type. The type attribute of a script tag will default to "text/javascript" if it is not otherwise specified. How that will affect validation, I'm not sure. But does that really matter anyway?

From - Why doesn't IE8 recognize type="application/javascript" in a script tag?

Upvotes: 4

Related Questions