Search code examples
jqueryhtmlcsssharepoint-2010

Why is my jQuery click handler not firing?


I've got this HTML in the *WebPartUserControl.ascx file of my Sharepoint 2010 Web Part project:

<html>
  <h1>Pre- and Post Travel Form Help</h1>
  <div id="preTravel" name="preTravel">
    <h2>Pre Travel</h2>
    <img id="imgPreTravel" name="imgPreTravel" src="/_layouts/images/TravelFormHelp/posttravelpdf.png" alt="pre Travel image" height="275" width="350">
  </div>
  <div id="postTravel" name="postTravel">
    <h2>Post Travel</h2>
    <img id="imgPostTravel" name="imgPostTravel" src="/_layouts/images/TravelFormHelp/posttravelpdf.png" alt="post Travel image" height="275" width="350">
  </div>
</html>

...and this jQuery:

<script type="text/javascript">
    $('imgPostTravel').click(function () {
        alert('you clicked the post Travel image');
        this.addClass('hide');
    });
</script>

The pertinent CSS is:

.hide {
  visibility: hidden;
  display: none;
}

When I click 'imgPostTravel', though, nothing happens - not only does the image not disappear, I don't see the alert.

As a sanity check (which I'm possibly failing), I tried similar code in a jsfiddle here and there, too the click handler is not firing - there must be something fundamentally daft about what I'm doing, but I can't see it...


Solution

  • This is a simple fix, just add a hashtag to your selector since it's an ID:

    $('#imgPostTravel').click(function () {