0

I have been struggling to figure out why my code is not working properly. I am working on a browser implementation of the game minesweeper, and am trying to get an image to hide() when the element is clicked. My html is as follows...

<img id="61" class="reveal" width="30px" height="30px" style="position:absolute;" src="img/tile.ico">

and my jquery looks like this...

    $( document ).ready(function() {
      $(".reveal").click(function(){
        $(this).attr("id").hide();
     });
  });

The problem seems to be my trying to grab the element id using $(this).attr("id").

user3468711
  • 143
  • 9
  • See also similar question: http://stackoverflow.com/questions/2711020/jquery-and-hide-a-div-on-a-click/2711199#2711199 – Kolban Oct 31 '14 at 14:56
  • why are you adding `$(this).attr("id").hide();`? do you need the ID for some reason? if not, you should just do this: `$(this).hide();` – CodeGodie Oct 31 '14 at 14:58

2 Answers2

2

Unless you are trying to target another element, simply hide this (which will be the class="reveal" element clicked):

  $( document ).ready(function() {
      $(".reveal").click(function(){
        $(this).hide();
     });
  });

The problem with your code is that attr returns a string, which you are then trying to run hide() on :)

Note: A better DOM-ready shortcut is simply:

  $(function() {
      $(".reveal").click(function(){
        $(this).hide();
     });
  });
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
  • Awesome. I was not expecting an answer that fast! This works for me. – user3468711 Oct 31 '14 at 15:06
  • 1
    @user3468711: fast is the name of the game here (*the quick or the point-less*) :) – iCollect.it Ltd Oct 31 '14 at 15:06
  • @user3468711 Yes it's know as *Fastest Gun in the West*. In problems like these most people can look at it and know the solution. But only the person who answers first gets the points. – Spencer Wieczorek Oct 31 '14 at 15:10
  • @Spencer Wieczorek: Indeed. I used to write answers like this under-appreciated one: http://stackoverflow.com/questions/6801546/silverlight-rotate-scale-a-bitmap-image-to-fit-within-rectangle-without-croppi/6802332#6802332 but not so much nowadays :) – iCollect.it Ltd Oct 31 '14 at 15:12
1

You're trying to hide the attribute with attr('id'), not the image. Use:

$( document ).ready(function() {
        $(".reveal").click(function(){
            $(this).hide();
        });
    });

to hide the image.

Refilon
  • 3,334
  • 1
  • 27
  • 51