views:

839

answers:

3

Why this does not work in IE/Chrome but works in FF/Opera? I want to make the div around anchor clickable, so that when you click div, it behaves the same as if you would click the anchor itself.

<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function bindOnClickPostBack() {
  $(".header a").each(function () { 
         var anchor = $(this);
            var clickEvent = anchor.attr('href');
            var header = anchor.parent();
            header.css('background-color', 'yellow');
            header.attr('onclick', clickEvent);
     });
  /*$(".header").live("click", function(){
   anchor = $(this).find('a');
   var clickEvent = anchor.attr('href');
   alert(clickEvent);
   $(this).css('background-color', 'yellow');
   //header.attr('onclick', clickEvent);
   //anchor.click();
     });*/
  return false;
    }

    $(document).ready(function() {
        bindOnClickPostBack();
    });
</script>

body:

<div style="background-color:red" class="header"> <a href="alert('hello1')">Shortcut1</a></div>
<div style="background-color:red" class="header"> <a href="alert('hello2')">Shortcut2</a></div>
<div style="background-color:red" class="header"> <a href="alert('hello3')">Shortcut3</a></div>
<div style="background-color:red" class="header"> <a href="alert('hello4')">Shortcut4</a></div>
+2  A: 

Since you're using jquery, try this:

$(document).ready(function() {
    $('div.header').click(function() {
       $(this).find('a').click();
    });
});
David Hedlund
+4  A: 

Um... why would you want to do that? If you want the whole header to be clickable, just make a big block-level anchor:

<a href="#" class="header">Big Header</a>

with:

a.header { display: block; width: 100%; height: 50px; background: yellow; }

and

$("a.header").click(function() {
  // do stuff
  return false;
});

or maybe the href is enough in this case.

If you really want to go down the route you are (and I would recommend against it), you need to find out what's in the href attribute. Different browsers might be massaging it somewhat.

The more normal way to bind a click event is:

$("div.header").click(function() {
  // do stuff
});

not mess with the onclick attribute directly.

Alternatively you could do:

$("div.header").click(function() {
  return $("a". this).click();
});

but again: why not just make the anchor large enough to be the header, making it a block level element if necessary?

cletus
A: 

+1 for cletus' answer, but I'll also add - event delegation.

Pawel Krakowiak